dev.c 311 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * NET3 Protocol independent device support routines.
  4. *
  5. * Derived from the non IP parts of dev.c 1.0.19
  6. * Authors: Ross Biro
  7. * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
  8. * Mark Evans, <evansmp@uhura.aston.ac.uk>
  9. *
  10. * Additional Authors:
  11. * Florian la Roche <rzsfl@rz.uni-sb.de>
  12. * Alan Cox <gw4pts@gw4pts.ampr.org>
  13. * David Hinds <dahinds@users.sourceforge.net>
  14. * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
  15. * Adam Sulmicki <adam@cfar.umd.edu>
  16. * Pekka Riikonen <priikone@poesidon.pspt.fi>
  17. *
  18. * Changes:
  19. * D.J. Barrow : Fixed bug where dev->refcnt gets set
  20. * to 2 if register_netdev gets called
  21. * before net_dev_init & also removed a
  22. * few lines of code in the process.
  23. * Alan Cox : device private ioctl copies fields back.
  24. * Alan Cox : Transmit queue code does relevant
  25. * stunts to keep the queue safe.
  26. * Alan Cox : Fixed double lock.
  27. * Alan Cox : Fixed promisc NULL pointer trap
  28. * ???????? : Support the full private ioctl range
  29. * Alan Cox : Moved ioctl permission check into
  30. * drivers
  31. * Tim Kordas : SIOCADDMULTI/SIOCDELMULTI
  32. * Alan Cox : 100 backlog just doesn't cut it when
  33. * you start doing multicast video 8)
  34. * Alan Cox : Rewrote net_bh and list manager.
  35. * Alan Cox : Fix ETH_P_ALL echoback lengths.
  36. * Alan Cox : Took out transmit every packet pass
  37. * Saved a few bytes in the ioctl handler
  38. * Alan Cox : Network driver sets packet type before
  39. * calling netif_rx. Saves a function
  40. * call a packet.
  41. * Alan Cox : Hashed net_bh()
  42. * Richard Kooijman: Timestamp fixes.
  43. * Alan Cox : Wrong field in SIOCGIFDSTADDR
  44. * Alan Cox : Device lock protection.
  45. * Alan Cox : Fixed nasty side effect of device close
  46. * changes.
  47. * Rudi Cilibrasi : Pass the right thing to
  48. * set_mac_address()
  49. * Dave Miller : 32bit quantity for the device lock to
  50. * make it work out on a Sparc.
  51. * Bjorn Ekwall : Added KERNELD hack.
  52. * Alan Cox : Cleaned up the backlog initialise.
  53. * Craig Metz : SIOCGIFCONF fix if space for under
  54. * 1 device.
  55. * Thomas Bogendoerfer : Return ENODEV for dev_open, if there
  56. * is no device open function.
  57. * Andi Kleen : Fix error reporting for SIOCGIFCONF
  58. * Michael Chastain : Fix signed/unsigned for SIOCGIFCONF
  59. * Cyrus Durgin : Cleaned for KMOD
  60. * Adam Sulmicki : Bug Fix : Network Device Unload
  61. * A network device unload needs to purge
  62. * the backlog queue.
  63. * Paul Rusty Russell : SIOCSIFNAME
  64. * Pekka Riikonen : Netdev boot-time settings code
  65. * Andrew Morton : Make unregister_netdevice wait
  66. * indefinitely on dev->refcnt
  67. * J Hadi Salim : - Backlog queue sampling
  68. * - netif_rx() feedback
  69. */
  70. #include <linux/uaccess.h>
  71. #include <linux/bitmap.h>
  72. #include <linux/capability.h>
  73. #include <linux/cpu.h>
  74. #include <linux/types.h>
  75. #include <linux/kernel.h>
  76. #include <linux/hash.h>
  77. #include <linux/slab.h>
  78. #include <linux/sched.h>
  79. #include <linux/sched/isolation.h>
  80. #include <linux/sched/mm.h>
  81. #include <linux/smpboot.h>
  82. #include <linux/mutex.h>
  83. #include <linux/rwsem.h>
  84. #include <linux/string.h>
  85. #include <linux/mm.h>
  86. #include <linux/socket.h>
  87. #include <linux/sockios.h>
  88. #include <linux/errno.h>
  89. #include <linux/interrupt.h>
  90. #include <linux/if_ether.h>
  91. #include <linux/netdevice.h>
  92. #include <linux/etherdevice.h>
  93. #include <linux/ethtool.h>
  94. #include <linux/skbuff.h>
  95. #include <linux/kthread.h>
  96. #include <linux/bpf.h>
  97. #include <linux/bpf_trace.h>
  98. #include <net/net_namespace.h>
  99. #include <net/sock.h>
  100. #include <net/busy_poll.h>
  101. #include <linux/rtnetlink.h>
  102. #include <linux/stat.h>
  103. #include <net/dsa.h>
  104. #include <net/dst.h>
  105. #include <net/dst_metadata.h>
  106. #include <net/gro.h>
  107. #include <net/pkt_sched.h>
  108. #include <net/pkt_cls.h>
  109. #include <net/checksum.h>
  110. #include <net/xfrm.h>
  111. #include <net/tcx.h>
  112. #include <linux/highmem.h>
  113. #include <linux/init.h>
  114. #include <linux/module.h>
  115. #include <linux/netpoll.h>
  116. #include <linux/rcupdate.h>
  117. #include <linux/delay.h>
  118. #include <net/iw_handler.h>
  119. #include <asm/current.h>
  120. #include <linux/audit.h>
  121. #include <linux/dmaengine.h>
  122. #include <linux/err.h>
  123. #include <linux/ctype.h>
  124. #include <linux/if_arp.h>
  125. #include <linux/if_vlan.h>
  126. #include <linux/ip.h>
  127. #include <net/ip.h>
  128. #include <net/mpls.h>
  129. #include <linux/ipv6.h>
  130. #include <linux/in.h>
  131. #include <linux/jhash.h>
  132. #include <linux/random.h>
  133. #include <trace/events/napi.h>
  134. #include <trace/events/net.h>
  135. #include <trace/events/skb.h>
  136. #include <trace/events/qdisc.h>
  137. #include <trace/events/xdp.h>
  138. #include <linux/inetdevice.h>
  139. #include <linux/cpu_rmap.h>
  140. #include <linux/static_key.h>
  141. #include <linux/hashtable.h>
  142. #include <linux/vmalloc.h>
  143. #include <linux/if_macvlan.h>
  144. #include <linux/errqueue.h>
  145. #include <linux/hrtimer.h>
  146. #include <linux/netfilter_netdev.h>
  147. #include <linux/crash_dump.h>
  148. #include <linux/sctp.h>
  149. #include <net/udp_tunnel.h>
  150. #include <linux/net_namespace.h>
  151. #include <linux/indirect_call_wrapper.h>
  152. #include <net/devlink.h>
  153. #include <linux/pm_runtime.h>
  154. #include <linux/prandom.h>
  155. #include <linux/once_lite.h>
  156. #include <net/netdev_rx_queue.h>
  157. #include <net/page_pool/types.h>
  158. #include <net/page_pool/helpers.h>
  159. #include <net/rps.h>
  160. #include <linux/phy_link_topology.h>
  161. #include "dev.h"
  162. #include "devmem.h"
  163. #include "net-sysfs.h"
  164. static DEFINE_SPINLOCK(ptype_lock);
  165. struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
  166. static int netif_rx_internal(struct sk_buff *skb);
  167. static int call_netdevice_notifiers_extack(unsigned long val,
  168. struct net_device *dev,
  169. struct netlink_ext_ack *extack);
  170. static DEFINE_MUTEX(ifalias_mutex);
  171. /* protects napi_hash addition/deletion and napi_gen_id */
  172. static DEFINE_SPINLOCK(napi_hash_lock);
  173. static unsigned int napi_gen_id = NR_CPUS;
  174. static DEFINE_READ_MOSTLY_HASHTABLE(napi_hash, 8);
  175. static DECLARE_RWSEM(devnet_rename_sem);
  176. static inline void dev_base_seq_inc(struct net *net)
  177. {
  178. unsigned int val = net->dev_base_seq + 1;
  179. WRITE_ONCE(net->dev_base_seq, val ?: 1);
  180. }
  181. static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
  182. {
  183. unsigned int hash = full_name_hash(net, name, strnlen(name, IFNAMSIZ));
  184. return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
  185. }
  186. static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
  187. {
  188. return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
  189. }
  190. #ifndef CONFIG_PREEMPT_RT
  191. static DEFINE_STATIC_KEY_FALSE(use_backlog_threads_key);
  192. static int __init setup_backlog_napi_threads(char *arg)
  193. {
  194. static_branch_enable(&use_backlog_threads_key);
  195. return 0;
  196. }
  197. early_param("thread_backlog_napi", setup_backlog_napi_threads);
  198. static bool use_backlog_threads(void)
  199. {
  200. return static_branch_unlikely(&use_backlog_threads_key);
  201. }
  202. #else
  203. static bool use_backlog_threads(void)
  204. {
  205. return true;
  206. }
  207. #endif
  208. static inline void backlog_lock_irq_save(struct softnet_data *sd,
  209. unsigned long *flags)
  210. {
  211. if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
  212. spin_lock_irqsave(&sd->input_pkt_queue.lock, *flags);
  213. else
  214. local_irq_save(*flags);
  215. }
  216. static inline void backlog_lock_irq_disable(struct softnet_data *sd)
  217. {
  218. if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
  219. spin_lock_irq(&sd->input_pkt_queue.lock);
  220. else
  221. local_irq_disable();
  222. }
  223. static inline void backlog_unlock_irq_restore(struct softnet_data *sd,
  224. unsigned long *flags)
  225. {
  226. if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
  227. spin_unlock_irqrestore(&sd->input_pkt_queue.lock, *flags);
  228. else
  229. local_irq_restore(*flags);
  230. }
  231. static inline void backlog_unlock_irq_enable(struct softnet_data *sd)
  232. {
  233. if (IS_ENABLED(CONFIG_RPS) || use_backlog_threads())
  234. spin_unlock_irq(&sd->input_pkt_queue.lock);
  235. else
  236. local_irq_enable();
  237. }
  238. static struct netdev_name_node *netdev_name_node_alloc(struct net_device *dev,
  239. const char *name)
  240. {
  241. struct netdev_name_node *name_node;
  242. name_node = kmalloc(sizeof(*name_node), GFP_KERNEL);
  243. if (!name_node)
  244. return NULL;
  245. INIT_HLIST_NODE(&name_node->hlist);
  246. name_node->dev = dev;
  247. name_node->name = name;
  248. return name_node;
  249. }
  250. static struct netdev_name_node *
  251. netdev_name_node_head_alloc(struct net_device *dev)
  252. {
  253. struct netdev_name_node *name_node;
  254. name_node = netdev_name_node_alloc(dev, dev->name);
  255. if (!name_node)
  256. return NULL;
  257. INIT_LIST_HEAD(&name_node->list);
  258. return name_node;
  259. }
  260. static void netdev_name_node_free(struct netdev_name_node *name_node)
  261. {
  262. kfree(name_node);
  263. }
  264. static void netdev_name_node_add(struct net *net,
  265. struct netdev_name_node *name_node)
  266. {
  267. hlist_add_head_rcu(&name_node->hlist,
  268. dev_name_hash(net, name_node->name));
  269. }
  270. static void netdev_name_node_del(struct netdev_name_node *name_node)
  271. {
  272. hlist_del_rcu(&name_node->hlist);
  273. }
  274. static struct netdev_name_node *netdev_name_node_lookup(struct net *net,
  275. const char *name)
  276. {
  277. struct hlist_head *head = dev_name_hash(net, name);
  278. struct netdev_name_node *name_node;
  279. hlist_for_each_entry(name_node, head, hlist)
  280. if (!strcmp(name_node->name, name))
  281. return name_node;
  282. return NULL;
  283. }
  284. static struct netdev_name_node *netdev_name_node_lookup_rcu(struct net *net,
  285. const char *name)
  286. {
  287. struct hlist_head *head = dev_name_hash(net, name);
  288. struct netdev_name_node *name_node;
  289. hlist_for_each_entry_rcu(name_node, head, hlist)
  290. if (!strcmp(name_node->name, name))
  291. return name_node;
  292. return NULL;
  293. }
  294. bool netdev_name_in_use(struct net *net, const char *name)
  295. {
  296. return netdev_name_node_lookup(net, name);
  297. }
  298. EXPORT_SYMBOL(netdev_name_in_use);
  299. int netdev_name_node_alt_create(struct net_device *dev, const char *name)
  300. {
  301. struct netdev_name_node *name_node;
  302. struct net *net = dev_net(dev);
  303. name_node = netdev_name_node_lookup(net, name);
  304. if (name_node)
  305. return -EEXIST;
  306. name_node = netdev_name_node_alloc(dev, name);
  307. if (!name_node)
  308. return -ENOMEM;
  309. netdev_name_node_add(net, name_node);
  310. /* The node that holds dev->name acts as a head of per-device list. */
  311. list_add_tail_rcu(&name_node->list, &dev->name_node->list);
  312. return 0;
  313. }
  314. static void netdev_name_node_alt_free(struct rcu_head *head)
  315. {
  316. struct netdev_name_node *name_node =
  317. container_of(head, struct netdev_name_node, rcu);
  318. kfree(name_node->name);
  319. netdev_name_node_free(name_node);
  320. }
  321. static void __netdev_name_node_alt_destroy(struct netdev_name_node *name_node)
  322. {
  323. netdev_name_node_del(name_node);
  324. list_del(&name_node->list);
  325. call_rcu(&name_node->rcu, netdev_name_node_alt_free);
  326. }
  327. int netdev_name_node_alt_destroy(struct net_device *dev, const char *name)
  328. {
  329. struct netdev_name_node *name_node;
  330. struct net *net = dev_net(dev);
  331. name_node = netdev_name_node_lookup(net, name);
  332. if (!name_node)
  333. return -ENOENT;
  334. /* lookup might have found our primary name or a name belonging
  335. * to another device.
  336. */
  337. if (name_node == dev->name_node || name_node->dev != dev)
  338. return -EINVAL;
  339. __netdev_name_node_alt_destroy(name_node);
  340. return 0;
  341. }
  342. static void netdev_name_node_alt_flush(struct net_device *dev)
  343. {
  344. struct netdev_name_node *name_node, *tmp;
  345. list_for_each_entry_safe(name_node, tmp, &dev->name_node->list, list) {
  346. list_del(&name_node->list);
  347. netdev_name_node_alt_free(&name_node->rcu);
  348. }
  349. }
  350. /* Device list insertion */
  351. static void list_netdevice(struct net_device *dev)
  352. {
  353. struct netdev_name_node *name_node;
  354. struct net *net = dev_net(dev);
  355. ASSERT_RTNL();
  356. list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
  357. netdev_name_node_add(net, dev->name_node);
  358. hlist_add_head_rcu(&dev->index_hlist,
  359. dev_index_hash(net, dev->ifindex));
  360. netdev_for_each_altname(dev, name_node)
  361. netdev_name_node_add(net, name_node);
  362. /* We reserved the ifindex, this can't fail */
  363. WARN_ON(xa_store(&net->dev_by_index, dev->ifindex, dev, GFP_KERNEL));
  364. dev_base_seq_inc(net);
  365. }
  366. /* Device list removal
  367. * caller must respect a RCU grace period before freeing/reusing dev
  368. */
  369. static void unlist_netdevice(struct net_device *dev)
  370. {
  371. struct netdev_name_node *name_node;
  372. struct net *net = dev_net(dev);
  373. ASSERT_RTNL();
  374. xa_erase(&net->dev_by_index, dev->ifindex);
  375. netdev_for_each_altname(dev, name_node)
  376. netdev_name_node_del(name_node);
  377. /* Unlink dev from the device chain */
  378. list_del_rcu(&dev->dev_list);
  379. netdev_name_node_del(dev->name_node);
  380. hlist_del_rcu(&dev->index_hlist);
  381. dev_base_seq_inc(dev_net(dev));
  382. }
  383. /*
  384. * Our notifier list
  385. */
  386. static RAW_NOTIFIER_HEAD(netdev_chain);
  387. /*
  388. * Device drivers call our routines to queue packets here. We empty the
  389. * queue in the local softnet handler.
  390. */
  391. DEFINE_PER_CPU_ALIGNED(struct softnet_data, softnet_data) = {
  392. .process_queue_bh_lock = INIT_LOCAL_LOCK(process_queue_bh_lock),
  393. };
  394. EXPORT_PER_CPU_SYMBOL(softnet_data);
  395. /* Page_pool has a lockless array/stack to alloc/recycle pages.
  396. * PP consumers must pay attention to run APIs in the appropriate context
  397. * (e.g. NAPI context).
  398. */
  399. static DEFINE_PER_CPU(struct page_pool *, system_page_pool);
  400. #ifdef CONFIG_LOCKDEP
  401. /*
  402. * register_netdevice() inits txq->_xmit_lock and sets lockdep class
  403. * according to dev->type
  404. */
  405. static const unsigned short netdev_lock_type[] = {
  406. ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
  407. ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
  408. ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
  409. ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
  410. ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
  411. ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
  412. ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
  413. ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
  414. ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
  415. ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
  416. ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
  417. ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
  418. ARPHRD_FCFABRIC, ARPHRD_IEEE80211, ARPHRD_IEEE80211_PRISM,
  419. ARPHRD_IEEE80211_RADIOTAP, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
  420. ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
  421. static const char *const netdev_lock_name[] = {
  422. "_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
  423. "_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
  424. "_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
  425. "_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
  426. "_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
  427. "_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
  428. "_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
  429. "_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
  430. "_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
  431. "_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
  432. "_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
  433. "_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
  434. "_xmit_FCFABRIC", "_xmit_IEEE80211", "_xmit_IEEE80211_PRISM",
  435. "_xmit_IEEE80211_RADIOTAP", "_xmit_PHONET", "_xmit_PHONET_PIPE",
  436. "_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
  437. static struct lock_class_key netdev_xmit_lock_key[ARRAY_SIZE(netdev_lock_type)];
  438. static struct lock_class_key netdev_addr_lock_key[ARRAY_SIZE(netdev_lock_type)];
  439. static inline unsigned short netdev_lock_pos(unsigned short dev_type)
  440. {
  441. int i;
  442. for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
  443. if (netdev_lock_type[i] == dev_type)
  444. return i;
  445. /* the last key is used by default */
  446. return ARRAY_SIZE(netdev_lock_type) - 1;
  447. }
  448. static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
  449. unsigned short dev_type)
  450. {
  451. int i;
  452. i = netdev_lock_pos(dev_type);
  453. lockdep_set_class_and_name(lock, &netdev_xmit_lock_key[i],
  454. netdev_lock_name[i]);
  455. }
  456. static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
  457. {
  458. int i;
  459. i = netdev_lock_pos(dev->type);
  460. lockdep_set_class_and_name(&dev->addr_list_lock,
  461. &netdev_addr_lock_key[i],
  462. netdev_lock_name[i]);
  463. }
  464. #else
  465. static inline void netdev_set_xmit_lockdep_class(spinlock_t *lock,
  466. unsigned short dev_type)
  467. {
  468. }
  469. static inline void netdev_set_addr_lockdep_class(struct net_device *dev)
  470. {
  471. }
  472. #endif
  473. /*******************************************************************************
  474. *
  475. * Protocol management and registration routines
  476. *
  477. *******************************************************************************/
  478. /*
  479. * Add a protocol ID to the list. Now that the input handler is
  480. * smarter we can dispense with all the messy stuff that used to be
  481. * here.
  482. *
  483. * BEWARE!!! Protocol handlers, mangling input packets,
  484. * MUST BE last in hash buckets and checking protocol handlers
  485. * MUST start from promiscuous ptype_all chain in net_bh.
  486. * It is true now, do not change it.
  487. * Explanation follows: if protocol handler, mangling packet, will
  488. * be the first on list, it is not able to sense, that packet
  489. * is cloned and should be copied-on-write, so that it will
  490. * change it and subsequent readers will get broken packet.
  491. * --ANK (980803)
  492. */
  493. static inline struct list_head *ptype_head(const struct packet_type *pt)
  494. {
  495. if (pt->type == htons(ETH_P_ALL))
  496. return pt->dev ? &pt->dev->ptype_all : &net_hotdata.ptype_all;
  497. else
  498. return pt->dev ? &pt->dev->ptype_specific :
  499. &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
  500. }
  501. /**
  502. * dev_add_pack - add packet handler
  503. * @pt: packet type declaration
  504. *
  505. * Add a protocol handler to the networking stack. The passed &packet_type
  506. * is linked into kernel lists and may not be freed until it has been
  507. * removed from the kernel lists.
  508. *
  509. * This call does not sleep therefore it can not
  510. * guarantee all CPU's that are in middle of receiving packets
  511. * will see the new packet type (until the next received packet).
  512. */
  513. void dev_add_pack(struct packet_type *pt)
  514. {
  515. struct list_head *head = ptype_head(pt);
  516. spin_lock(&ptype_lock);
  517. list_add_rcu(&pt->list, head);
  518. spin_unlock(&ptype_lock);
  519. }
  520. EXPORT_SYMBOL(dev_add_pack);
  521. /**
  522. * __dev_remove_pack - remove packet handler
  523. * @pt: packet type declaration
  524. *
  525. * Remove a protocol handler that was previously added to the kernel
  526. * protocol handlers by dev_add_pack(). The passed &packet_type is removed
  527. * from the kernel lists and can be freed or reused once this function
  528. * returns.
  529. *
  530. * The packet type might still be in use by receivers
  531. * and must not be freed until after all the CPU's have gone
  532. * through a quiescent state.
  533. */
  534. void __dev_remove_pack(struct packet_type *pt)
  535. {
  536. struct list_head *head = ptype_head(pt);
  537. struct packet_type *pt1;
  538. spin_lock(&ptype_lock);
  539. list_for_each_entry(pt1, head, list) {
  540. if (pt == pt1) {
  541. list_del_rcu(&pt->list);
  542. goto out;
  543. }
  544. }
  545. pr_warn("dev_remove_pack: %p not found\n", pt);
  546. out:
  547. spin_unlock(&ptype_lock);
  548. }
  549. EXPORT_SYMBOL(__dev_remove_pack);
  550. /**
  551. * dev_remove_pack - remove packet handler
  552. * @pt: packet type declaration
  553. *
  554. * Remove a protocol handler that was previously added to the kernel
  555. * protocol handlers by dev_add_pack(). The passed &packet_type is removed
  556. * from the kernel lists and can be freed or reused once this function
  557. * returns.
  558. *
  559. * This call sleeps to guarantee that no CPU is looking at the packet
  560. * type after return.
  561. */
  562. void dev_remove_pack(struct packet_type *pt)
  563. {
  564. __dev_remove_pack(pt);
  565. synchronize_net();
  566. }
  567. EXPORT_SYMBOL(dev_remove_pack);
  568. /*******************************************************************************
  569. *
  570. * Device Interface Subroutines
  571. *
  572. *******************************************************************************/
  573. /**
  574. * dev_get_iflink - get 'iflink' value of a interface
  575. * @dev: targeted interface
  576. *
  577. * Indicates the ifindex the interface is linked to.
  578. * Physical interfaces have the same 'ifindex' and 'iflink' values.
  579. */
  580. int dev_get_iflink(const struct net_device *dev)
  581. {
  582. if (dev->netdev_ops && dev->netdev_ops->ndo_get_iflink)
  583. return dev->netdev_ops->ndo_get_iflink(dev);
  584. return READ_ONCE(dev->ifindex);
  585. }
  586. EXPORT_SYMBOL(dev_get_iflink);
  587. /**
  588. * dev_fill_metadata_dst - Retrieve tunnel egress information.
  589. * @dev: targeted interface
  590. * @skb: The packet.
  591. *
  592. * For better visibility of tunnel traffic OVS needs to retrieve
  593. * egress tunnel information for a packet. Following API allows
  594. * user to get this info.
  595. */
  596. int dev_fill_metadata_dst(struct net_device *dev, struct sk_buff *skb)
  597. {
  598. struct ip_tunnel_info *info;
  599. if (!dev->netdev_ops || !dev->netdev_ops->ndo_fill_metadata_dst)
  600. return -EINVAL;
  601. info = skb_tunnel_info_unclone(skb);
  602. if (!info)
  603. return -ENOMEM;
  604. if (unlikely(!(info->mode & IP_TUNNEL_INFO_TX)))
  605. return -EINVAL;
  606. return dev->netdev_ops->ndo_fill_metadata_dst(dev, skb);
  607. }
  608. EXPORT_SYMBOL_GPL(dev_fill_metadata_dst);
  609. static struct net_device_path *dev_fwd_path(struct net_device_path_stack *stack)
  610. {
  611. int k = stack->num_paths++;
  612. if (WARN_ON_ONCE(k >= NET_DEVICE_PATH_STACK_MAX))
  613. return NULL;
  614. return &stack->path[k];
  615. }
  616. int dev_fill_forward_path(const struct net_device *dev, const u8 *daddr,
  617. struct net_device_path_stack *stack)
  618. {
  619. const struct net_device *last_dev;
  620. struct net_device_path_ctx ctx = {
  621. .dev = dev,
  622. };
  623. struct net_device_path *path;
  624. int ret = 0;
  625. memcpy(ctx.daddr, daddr, sizeof(ctx.daddr));
  626. stack->num_paths = 0;
  627. while (ctx.dev && ctx.dev->netdev_ops->ndo_fill_forward_path) {
  628. last_dev = ctx.dev;
  629. path = dev_fwd_path(stack);
  630. if (!path)
  631. return -1;
  632. memset(path, 0, sizeof(struct net_device_path));
  633. ret = ctx.dev->netdev_ops->ndo_fill_forward_path(&ctx, path);
  634. if (ret < 0)
  635. return -1;
  636. if (WARN_ON_ONCE(last_dev == ctx.dev))
  637. return -1;
  638. }
  639. if (!ctx.dev)
  640. return ret;
  641. path = dev_fwd_path(stack);
  642. if (!path)
  643. return -1;
  644. path->type = DEV_PATH_ETHERNET;
  645. path->dev = ctx.dev;
  646. return ret;
  647. }
  648. EXPORT_SYMBOL_GPL(dev_fill_forward_path);
  649. /* must be called under rcu_read_lock(), as we dont take a reference */
  650. static struct napi_struct *napi_by_id(unsigned int napi_id)
  651. {
  652. unsigned int hash = napi_id % HASH_SIZE(napi_hash);
  653. struct napi_struct *napi;
  654. hlist_for_each_entry_rcu(napi, &napi_hash[hash], napi_hash_node)
  655. if (napi->napi_id == napi_id)
  656. return napi;
  657. return NULL;
  658. }
  659. /* must be called under rcu_read_lock(), as we dont take a reference */
  660. struct napi_struct *netdev_napi_by_id(struct net *net, unsigned int napi_id)
  661. {
  662. struct napi_struct *napi;
  663. napi = napi_by_id(napi_id);
  664. if (!napi)
  665. return NULL;
  666. if (WARN_ON_ONCE(!napi->dev))
  667. return NULL;
  668. if (!net_eq(net, dev_net(napi->dev)))
  669. return NULL;
  670. return napi;
  671. }
  672. /**
  673. * __dev_get_by_name - find a device by its name
  674. * @net: the applicable net namespace
  675. * @name: name to find
  676. *
  677. * Find an interface by name. Must be called under RTNL semaphore.
  678. * If the name is found a pointer to the device is returned.
  679. * If the name is not found then %NULL is returned. The
  680. * reference counters are not incremented so the caller must be
  681. * careful with locks.
  682. */
  683. struct net_device *__dev_get_by_name(struct net *net, const char *name)
  684. {
  685. struct netdev_name_node *node_name;
  686. node_name = netdev_name_node_lookup(net, name);
  687. return node_name ? node_name->dev : NULL;
  688. }
  689. EXPORT_SYMBOL(__dev_get_by_name);
  690. /**
  691. * dev_get_by_name_rcu - find a device by its name
  692. * @net: the applicable net namespace
  693. * @name: name to find
  694. *
  695. * Find an interface by name.
  696. * If the name is found a pointer to the device is returned.
  697. * If the name is not found then %NULL is returned.
  698. * The reference counters are not incremented so the caller must be
  699. * careful with locks. The caller must hold RCU lock.
  700. */
  701. struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
  702. {
  703. struct netdev_name_node *node_name;
  704. node_name = netdev_name_node_lookup_rcu(net, name);
  705. return node_name ? node_name->dev : NULL;
  706. }
  707. EXPORT_SYMBOL(dev_get_by_name_rcu);
  708. /* Deprecated for new users, call netdev_get_by_name() instead */
  709. struct net_device *dev_get_by_name(struct net *net, const char *name)
  710. {
  711. struct net_device *dev;
  712. rcu_read_lock();
  713. dev = dev_get_by_name_rcu(net, name);
  714. dev_hold(dev);
  715. rcu_read_unlock();
  716. return dev;
  717. }
  718. EXPORT_SYMBOL(dev_get_by_name);
  719. /**
  720. * netdev_get_by_name() - find a device by its name
  721. * @net: the applicable net namespace
  722. * @name: name to find
  723. * @tracker: tracking object for the acquired reference
  724. * @gfp: allocation flags for the tracker
  725. *
  726. * Find an interface by name. This can be called from any
  727. * context and does its own locking. The returned handle has
  728. * the usage count incremented and the caller must use netdev_put() to
  729. * release it when it is no longer needed. %NULL is returned if no
  730. * matching device is found.
  731. */
  732. struct net_device *netdev_get_by_name(struct net *net, const char *name,
  733. netdevice_tracker *tracker, gfp_t gfp)
  734. {
  735. struct net_device *dev;
  736. dev = dev_get_by_name(net, name);
  737. if (dev)
  738. netdev_tracker_alloc(dev, tracker, gfp);
  739. return dev;
  740. }
  741. EXPORT_SYMBOL(netdev_get_by_name);
  742. /**
  743. * __dev_get_by_index - find a device by its ifindex
  744. * @net: the applicable net namespace
  745. * @ifindex: index of device
  746. *
  747. * Search for an interface by index. Returns %NULL if the device
  748. * is not found or a pointer to the device. The device has not
  749. * had its reference counter increased so the caller must be careful
  750. * about locking. The caller must hold the RTNL semaphore.
  751. */
  752. struct net_device *__dev_get_by_index(struct net *net, int ifindex)
  753. {
  754. struct net_device *dev;
  755. struct hlist_head *head = dev_index_hash(net, ifindex);
  756. hlist_for_each_entry(dev, head, index_hlist)
  757. if (dev->ifindex == ifindex)
  758. return dev;
  759. return NULL;
  760. }
  761. EXPORT_SYMBOL(__dev_get_by_index);
  762. /**
  763. * dev_get_by_index_rcu - find a device by its ifindex
  764. * @net: the applicable net namespace
  765. * @ifindex: index of device
  766. *
  767. * Search for an interface by index. Returns %NULL if the device
  768. * is not found or a pointer to the device. The device has not
  769. * had its reference counter increased so the caller must be careful
  770. * about locking. The caller must hold RCU lock.
  771. */
  772. struct net_device *dev_get_by_index_rcu(struct net *net, int ifindex)
  773. {
  774. struct net_device *dev;
  775. struct hlist_head *head = dev_index_hash(net, ifindex);
  776. hlist_for_each_entry_rcu(dev, head, index_hlist)
  777. if (dev->ifindex == ifindex)
  778. return dev;
  779. return NULL;
  780. }
  781. EXPORT_SYMBOL(dev_get_by_index_rcu);
  782. /* Deprecated for new users, call netdev_get_by_index() instead */
  783. struct net_device *dev_get_by_index(struct net *net, int ifindex)
  784. {
  785. struct net_device *dev;
  786. rcu_read_lock();
  787. dev = dev_get_by_index_rcu(net, ifindex);
  788. dev_hold(dev);
  789. rcu_read_unlock();
  790. return dev;
  791. }
  792. EXPORT_SYMBOL(dev_get_by_index);
  793. /**
  794. * netdev_get_by_index() - find a device by its ifindex
  795. * @net: the applicable net namespace
  796. * @ifindex: index of device
  797. * @tracker: tracking object for the acquired reference
  798. * @gfp: allocation flags for the tracker
  799. *
  800. * Search for an interface by index. Returns NULL if the device
  801. * is not found or a pointer to the device. The device returned has
  802. * had a reference added and the pointer is safe until the user calls
  803. * netdev_put() to indicate they have finished with it.
  804. */
  805. struct net_device *netdev_get_by_index(struct net *net, int ifindex,
  806. netdevice_tracker *tracker, gfp_t gfp)
  807. {
  808. struct net_device *dev;
  809. dev = dev_get_by_index(net, ifindex);
  810. if (dev)
  811. netdev_tracker_alloc(dev, tracker, gfp);
  812. return dev;
  813. }
  814. EXPORT_SYMBOL(netdev_get_by_index);
  815. /**
  816. * dev_get_by_napi_id - find a device by napi_id
  817. * @napi_id: ID of the NAPI struct
  818. *
  819. * Search for an interface by NAPI ID. Returns %NULL if the device
  820. * is not found or a pointer to the device. The device has not had
  821. * its reference counter increased so the caller must be careful
  822. * about locking. The caller must hold RCU lock.
  823. */
  824. struct net_device *dev_get_by_napi_id(unsigned int napi_id)
  825. {
  826. struct napi_struct *napi;
  827. WARN_ON_ONCE(!rcu_read_lock_held());
  828. if (napi_id < MIN_NAPI_ID)
  829. return NULL;
  830. napi = napi_by_id(napi_id);
  831. return napi ? napi->dev : NULL;
  832. }
  833. EXPORT_SYMBOL(dev_get_by_napi_id);
  834. static DEFINE_SEQLOCK(netdev_rename_lock);
  835. void netdev_copy_name(struct net_device *dev, char *name)
  836. {
  837. unsigned int seq;
  838. do {
  839. seq = read_seqbegin(&netdev_rename_lock);
  840. strscpy(name, dev->name, IFNAMSIZ);
  841. } while (read_seqretry(&netdev_rename_lock, seq));
  842. }
  843. /**
  844. * netdev_get_name - get a netdevice name, knowing its ifindex.
  845. * @net: network namespace
  846. * @name: a pointer to the buffer where the name will be stored.
  847. * @ifindex: the ifindex of the interface to get the name from.
  848. */
  849. int netdev_get_name(struct net *net, char *name, int ifindex)
  850. {
  851. struct net_device *dev;
  852. int ret;
  853. rcu_read_lock();
  854. dev = dev_get_by_index_rcu(net, ifindex);
  855. if (!dev) {
  856. ret = -ENODEV;
  857. goto out;
  858. }
  859. netdev_copy_name(dev, name);
  860. ret = 0;
  861. out:
  862. rcu_read_unlock();
  863. return ret;
  864. }
  865. static bool dev_addr_cmp(struct net_device *dev, unsigned short type,
  866. const char *ha)
  867. {
  868. return dev->type == type && !memcmp(dev->dev_addr, ha, dev->addr_len);
  869. }
  870. /**
  871. * dev_getbyhwaddr_rcu - find a device by its hardware address
  872. * @net: the applicable net namespace
  873. * @type: media type of device
  874. * @ha: hardware address
  875. *
  876. * Search for an interface by MAC address. Returns NULL if the device
  877. * is not found or a pointer to the device.
  878. * The caller must hold RCU.
  879. * The returned device has not had its ref count increased
  880. * and the caller must therefore be careful about locking
  881. *
  882. */
  883. struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
  884. const char *ha)
  885. {
  886. struct net_device *dev;
  887. for_each_netdev_rcu(net, dev)
  888. if (dev_addr_cmp(dev, type, ha))
  889. return dev;
  890. return NULL;
  891. }
  892. EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
  893. /**
  894. * dev_getbyhwaddr() - find a device by its hardware address
  895. * @net: the applicable net namespace
  896. * @type: media type of device
  897. * @ha: hardware address
  898. *
  899. * Similar to dev_getbyhwaddr_rcu(), but the owner needs to hold
  900. * rtnl_lock.
  901. *
  902. * Context: rtnl_lock() must be held.
  903. * Return: pointer to the net_device, or NULL if not found
  904. */
  905. struct net_device *dev_getbyhwaddr(struct net *net, unsigned short type,
  906. const char *ha)
  907. {
  908. struct net_device *dev;
  909. ASSERT_RTNL();
  910. for_each_netdev(net, dev)
  911. if (dev_addr_cmp(dev, type, ha))
  912. return dev;
  913. return NULL;
  914. }
  915. EXPORT_SYMBOL(dev_getbyhwaddr);
  916. struct net_device *dev_getfirstbyhwtype(struct net *net, unsigned short type)
  917. {
  918. struct net_device *dev, *ret = NULL;
  919. rcu_read_lock();
  920. for_each_netdev_rcu(net, dev)
  921. if (dev->type == type) {
  922. dev_hold(dev);
  923. ret = dev;
  924. break;
  925. }
  926. rcu_read_unlock();
  927. return ret;
  928. }
  929. EXPORT_SYMBOL(dev_getfirstbyhwtype);
  930. /**
  931. * __dev_get_by_flags - find any device with given flags
  932. * @net: the applicable net namespace
  933. * @if_flags: IFF_* values
  934. * @mask: bitmask of bits in if_flags to check
  935. *
  936. * Search for any interface with the given flags. Returns NULL if a device
  937. * is not found or a pointer to the device. Must be called inside
  938. * rtnl_lock(), and result refcount is unchanged.
  939. */
  940. struct net_device *__dev_get_by_flags(struct net *net, unsigned short if_flags,
  941. unsigned short mask)
  942. {
  943. struct net_device *dev, *ret;
  944. ASSERT_RTNL();
  945. ret = NULL;
  946. for_each_netdev(net, dev) {
  947. if (((dev->flags ^ if_flags) & mask) == 0) {
  948. ret = dev;
  949. break;
  950. }
  951. }
  952. return ret;
  953. }
  954. EXPORT_SYMBOL(__dev_get_by_flags);
  955. /**
  956. * dev_valid_name - check if name is okay for network device
  957. * @name: name string
  958. *
  959. * Network device names need to be valid file names to
  960. * allow sysfs to work. We also disallow any kind of
  961. * whitespace.
  962. */
  963. bool dev_valid_name(const char *name)
  964. {
  965. if (*name == '\0')
  966. return false;
  967. if (strnlen(name, IFNAMSIZ) == IFNAMSIZ)
  968. return false;
  969. if (!strcmp(name, ".") || !strcmp(name, ".."))
  970. return false;
  971. while (*name) {
  972. if (*name == '/' || *name == ':' || isspace(*name))
  973. return false;
  974. name++;
  975. }
  976. return true;
  977. }
  978. EXPORT_SYMBOL(dev_valid_name);
  979. /**
  980. * __dev_alloc_name - allocate a name for a device
  981. * @net: network namespace to allocate the device name in
  982. * @name: name format string
  983. * @res: result name string
  984. *
  985. * Passed a format string - eg "lt%d" it will try and find a suitable
  986. * id. It scans list of devices to build up a free map, then chooses
  987. * the first empty slot. The caller must hold the dev_base or rtnl lock
  988. * while allocating the name and adding the device in order to avoid
  989. * duplicates.
  990. * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
  991. * Returns the number of the unit assigned or a negative errno code.
  992. */
  993. static int __dev_alloc_name(struct net *net, const char *name, char *res)
  994. {
  995. int i = 0;
  996. const char *p;
  997. const int max_netdevices = 8*PAGE_SIZE;
  998. unsigned long *inuse;
  999. struct net_device *d;
  1000. char buf[IFNAMSIZ];
  1001. /* Verify the string as this thing may have come from the user.
  1002. * There must be one "%d" and no other "%" characters.
  1003. */
  1004. p = strchr(name, '%');
  1005. if (!p || p[1] != 'd' || strchr(p + 2, '%'))
  1006. return -EINVAL;
  1007. /* Use one page as a bit array of possible slots */
  1008. inuse = bitmap_zalloc(max_netdevices, GFP_ATOMIC);
  1009. if (!inuse)
  1010. return -ENOMEM;
  1011. for_each_netdev(net, d) {
  1012. struct netdev_name_node *name_node;
  1013. netdev_for_each_altname(d, name_node) {
  1014. if (!sscanf(name_node->name, name, &i))
  1015. continue;
  1016. if (i < 0 || i >= max_netdevices)
  1017. continue;
  1018. /* avoid cases where sscanf is not exact inverse of printf */
  1019. snprintf(buf, IFNAMSIZ, name, i);
  1020. if (!strncmp(buf, name_node->name, IFNAMSIZ))
  1021. __set_bit(i, inuse);
  1022. }
  1023. if (!sscanf(d->name, name, &i))
  1024. continue;
  1025. if (i < 0 || i >= max_netdevices)
  1026. continue;
  1027. /* avoid cases where sscanf is not exact inverse of printf */
  1028. snprintf(buf, IFNAMSIZ, name, i);
  1029. if (!strncmp(buf, d->name, IFNAMSIZ))
  1030. __set_bit(i, inuse);
  1031. }
  1032. i = find_first_zero_bit(inuse, max_netdevices);
  1033. bitmap_free(inuse);
  1034. if (i == max_netdevices)
  1035. return -ENFILE;
  1036. /* 'res' and 'name' could overlap, use 'buf' as an intermediate buffer */
  1037. strscpy(buf, name, IFNAMSIZ);
  1038. snprintf(res, IFNAMSIZ, buf, i);
  1039. return i;
  1040. }
  1041. /* Returns negative errno or allocated unit id (see __dev_alloc_name()) */
  1042. static int dev_prep_valid_name(struct net *net, struct net_device *dev,
  1043. const char *want_name, char *out_name,
  1044. int dup_errno)
  1045. {
  1046. if (!dev_valid_name(want_name))
  1047. return -EINVAL;
  1048. if (strchr(want_name, '%'))
  1049. return __dev_alloc_name(net, want_name, out_name);
  1050. if (netdev_name_in_use(net, want_name))
  1051. return -dup_errno;
  1052. if (out_name != want_name)
  1053. strscpy(out_name, want_name, IFNAMSIZ);
  1054. return 0;
  1055. }
  1056. /**
  1057. * dev_alloc_name - allocate a name for a device
  1058. * @dev: device
  1059. * @name: name format string
  1060. *
  1061. * Passed a format string - eg "lt%d" it will try and find a suitable
  1062. * id. It scans list of devices to build up a free map, then chooses
  1063. * the first empty slot. The caller must hold the dev_base or rtnl lock
  1064. * while allocating the name and adding the device in order to avoid
  1065. * duplicates.
  1066. * Limited to bits_per_byte * page size devices (ie 32K on most platforms).
  1067. * Returns the number of the unit assigned or a negative errno code.
  1068. */
  1069. int dev_alloc_name(struct net_device *dev, const char *name)
  1070. {
  1071. return dev_prep_valid_name(dev_net(dev), dev, name, dev->name, ENFILE);
  1072. }
  1073. EXPORT_SYMBOL(dev_alloc_name);
  1074. static int dev_get_valid_name(struct net *net, struct net_device *dev,
  1075. const char *name)
  1076. {
  1077. int ret;
  1078. ret = dev_prep_valid_name(net, dev, name, dev->name, EEXIST);
  1079. return ret < 0 ? ret : 0;
  1080. }
  1081. /**
  1082. * dev_change_name - change name of a device
  1083. * @dev: device
  1084. * @newname: name (or format string) must be at least IFNAMSIZ
  1085. *
  1086. * Change name of a device, can pass format strings "eth%d".
  1087. * for wildcarding.
  1088. */
  1089. int dev_change_name(struct net_device *dev, const char *newname)
  1090. {
  1091. unsigned char old_assign_type;
  1092. char oldname[IFNAMSIZ];
  1093. int err = 0;
  1094. int ret;
  1095. struct net *net;
  1096. ASSERT_RTNL();
  1097. BUG_ON(!dev_net(dev));
  1098. net = dev_net(dev);
  1099. down_write(&devnet_rename_sem);
  1100. if (strncmp(newname, dev->name, IFNAMSIZ) == 0) {
  1101. up_write(&devnet_rename_sem);
  1102. return 0;
  1103. }
  1104. memcpy(oldname, dev->name, IFNAMSIZ);
  1105. write_seqlock_bh(&netdev_rename_lock);
  1106. err = dev_get_valid_name(net, dev, newname);
  1107. write_sequnlock_bh(&netdev_rename_lock);
  1108. if (err < 0) {
  1109. up_write(&devnet_rename_sem);
  1110. return err;
  1111. }
  1112. if (oldname[0] && !strchr(oldname, '%'))
  1113. netdev_info(dev, "renamed from %s%s\n", oldname,
  1114. dev->flags & IFF_UP ? " (while UP)" : "");
  1115. old_assign_type = dev->name_assign_type;
  1116. WRITE_ONCE(dev->name_assign_type, NET_NAME_RENAMED);
  1117. rollback:
  1118. ret = device_rename(&dev->dev, dev->name);
  1119. if (ret) {
  1120. write_seqlock_bh(&netdev_rename_lock);
  1121. memcpy(dev->name, oldname, IFNAMSIZ);
  1122. write_sequnlock_bh(&netdev_rename_lock);
  1123. WRITE_ONCE(dev->name_assign_type, old_assign_type);
  1124. up_write(&devnet_rename_sem);
  1125. return ret;
  1126. }
  1127. up_write(&devnet_rename_sem);
  1128. netdev_adjacent_rename_links(dev, oldname);
  1129. netdev_name_node_del(dev->name_node);
  1130. synchronize_net();
  1131. netdev_name_node_add(net, dev->name_node);
  1132. ret = call_netdevice_notifiers(NETDEV_CHANGENAME, dev);
  1133. ret = notifier_to_errno(ret);
  1134. if (ret) {
  1135. /* err >= 0 after dev_alloc_name() or stores the first errno */
  1136. if (err >= 0) {
  1137. err = ret;
  1138. down_write(&devnet_rename_sem);
  1139. write_seqlock_bh(&netdev_rename_lock);
  1140. memcpy(dev->name, oldname, IFNAMSIZ);
  1141. write_sequnlock_bh(&netdev_rename_lock);
  1142. memcpy(oldname, newname, IFNAMSIZ);
  1143. WRITE_ONCE(dev->name_assign_type, old_assign_type);
  1144. old_assign_type = NET_NAME_RENAMED;
  1145. goto rollback;
  1146. } else {
  1147. netdev_err(dev, "name change rollback failed: %d\n",
  1148. ret);
  1149. }
  1150. }
  1151. return err;
  1152. }
  1153. /**
  1154. * dev_set_alias - change ifalias of a device
  1155. * @dev: device
  1156. * @alias: name up to IFALIASZ
  1157. * @len: limit of bytes to copy from info
  1158. *
  1159. * Set ifalias for a device,
  1160. */
  1161. int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
  1162. {
  1163. struct dev_ifalias *new_alias = NULL;
  1164. if (len >= IFALIASZ)
  1165. return -EINVAL;
  1166. if (len) {
  1167. new_alias = kmalloc(sizeof(*new_alias) + len + 1, GFP_KERNEL);
  1168. if (!new_alias)
  1169. return -ENOMEM;
  1170. memcpy(new_alias->ifalias, alias, len);
  1171. new_alias->ifalias[len] = 0;
  1172. }
  1173. mutex_lock(&ifalias_mutex);
  1174. new_alias = rcu_replace_pointer(dev->ifalias, new_alias,
  1175. mutex_is_locked(&ifalias_mutex));
  1176. mutex_unlock(&ifalias_mutex);
  1177. if (new_alias)
  1178. kfree_rcu(new_alias, rcuhead);
  1179. return len;
  1180. }
  1181. EXPORT_SYMBOL(dev_set_alias);
  1182. /**
  1183. * dev_get_alias - get ifalias of a device
  1184. * @dev: device
  1185. * @name: buffer to store name of ifalias
  1186. * @len: size of buffer
  1187. *
  1188. * get ifalias for a device. Caller must make sure dev cannot go
  1189. * away, e.g. rcu read lock or own a reference count to device.
  1190. */
  1191. int dev_get_alias(const struct net_device *dev, char *name, size_t len)
  1192. {
  1193. const struct dev_ifalias *alias;
  1194. int ret = 0;
  1195. rcu_read_lock();
  1196. alias = rcu_dereference(dev->ifalias);
  1197. if (alias)
  1198. ret = snprintf(name, len, "%s", alias->ifalias);
  1199. rcu_read_unlock();
  1200. return ret;
  1201. }
  1202. /**
  1203. * netdev_features_change - device changes features
  1204. * @dev: device to cause notification
  1205. *
  1206. * Called to indicate a device has changed features.
  1207. */
  1208. void netdev_features_change(struct net_device *dev)
  1209. {
  1210. call_netdevice_notifiers(NETDEV_FEAT_CHANGE, dev);
  1211. }
  1212. EXPORT_SYMBOL(netdev_features_change);
  1213. /**
  1214. * netdev_state_change - device changes state
  1215. * @dev: device to cause notification
  1216. *
  1217. * Called to indicate a device has changed state. This function calls
  1218. * the notifier chains for netdev_chain and sends a NEWLINK message
  1219. * to the routing socket.
  1220. */
  1221. void netdev_state_change(struct net_device *dev)
  1222. {
  1223. if (dev->flags & IFF_UP) {
  1224. struct netdev_notifier_change_info change_info = {
  1225. .info.dev = dev,
  1226. };
  1227. call_netdevice_notifiers_info(NETDEV_CHANGE,
  1228. &change_info.info);
  1229. rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL, 0, NULL);
  1230. }
  1231. }
  1232. EXPORT_SYMBOL(netdev_state_change);
  1233. /**
  1234. * __netdev_notify_peers - notify network peers about existence of @dev,
  1235. * to be called when rtnl lock is already held.
  1236. * @dev: network device
  1237. *
  1238. * Generate traffic such that interested network peers are aware of
  1239. * @dev, such as by generating a gratuitous ARP. This may be used when
  1240. * a device wants to inform the rest of the network about some sort of
  1241. * reconfiguration such as a failover event or virtual machine
  1242. * migration.
  1243. */
  1244. void __netdev_notify_peers(struct net_device *dev)
  1245. {
  1246. ASSERT_RTNL();
  1247. call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, dev);
  1248. call_netdevice_notifiers(NETDEV_RESEND_IGMP, dev);
  1249. }
  1250. EXPORT_SYMBOL(__netdev_notify_peers);
  1251. /**
  1252. * netdev_notify_peers - notify network peers about existence of @dev
  1253. * @dev: network device
  1254. *
  1255. * Generate traffic such that interested network peers are aware of
  1256. * @dev, such as by generating a gratuitous ARP. This may be used when
  1257. * a device wants to inform the rest of the network about some sort of
  1258. * reconfiguration such as a failover event or virtual machine
  1259. * migration.
  1260. */
  1261. void netdev_notify_peers(struct net_device *dev)
  1262. {
  1263. rtnl_lock();
  1264. __netdev_notify_peers(dev);
  1265. rtnl_unlock();
  1266. }
  1267. EXPORT_SYMBOL(netdev_notify_peers);
  1268. static int napi_threaded_poll(void *data);
  1269. static int napi_kthread_create(struct napi_struct *n)
  1270. {
  1271. int err = 0;
  1272. /* Create and wake up the kthread once to put it in
  1273. * TASK_INTERRUPTIBLE mode to avoid the blocked task
  1274. * warning and work with loadavg.
  1275. */
  1276. n->thread = kthread_run(napi_threaded_poll, n, "napi/%s-%d",
  1277. n->dev->name, n->napi_id);
  1278. if (IS_ERR(n->thread)) {
  1279. err = PTR_ERR(n->thread);
  1280. pr_err("kthread_run failed with err %d\n", err);
  1281. n->thread = NULL;
  1282. }
  1283. return err;
  1284. }
  1285. static int __dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
  1286. {
  1287. const struct net_device_ops *ops = dev->netdev_ops;
  1288. int ret;
  1289. ASSERT_RTNL();
  1290. dev_addr_check(dev);
  1291. if (!netif_device_present(dev)) {
  1292. /* may be detached because parent is runtime-suspended */
  1293. if (dev->dev.parent)
  1294. pm_runtime_resume(dev->dev.parent);
  1295. if (!netif_device_present(dev))
  1296. return -ENODEV;
  1297. }
  1298. /* Block netpoll from trying to do any rx path servicing.
  1299. * If we don't do this there is a chance ndo_poll_controller
  1300. * or ndo_poll may be running while we open the device
  1301. */
  1302. netpoll_poll_disable(dev);
  1303. ret = call_netdevice_notifiers_extack(NETDEV_PRE_UP, dev, extack);
  1304. ret = notifier_to_errno(ret);
  1305. if (ret)
  1306. return ret;
  1307. set_bit(__LINK_STATE_START, &dev->state);
  1308. if (ops->ndo_validate_addr)
  1309. ret = ops->ndo_validate_addr(dev);
  1310. if (!ret && ops->ndo_open)
  1311. ret = ops->ndo_open(dev);
  1312. netpoll_poll_enable(dev);
  1313. if (ret)
  1314. clear_bit(__LINK_STATE_START, &dev->state);
  1315. else {
  1316. dev->flags |= IFF_UP;
  1317. dev_set_rx_mode(dev);
  1318. dev_activate(dev);
  1319. add_device_randomness(dev->dev_addr, dev->addr_len);
  1320. }
  1321. return ret;
  1322. }
  1323. /**
  1324. * dev_open - prepare an interface for use.
  1325. * @dev: device to open
  1326. * @extack: netlink extended ack
  1327. *
  1328. * Takes a device from down to up state. The device's private open
  1329. * function is invoked and then the multicast lists are loaded. Finally
  1330. * the device is moved into the up state and a %NETDEV_UP message is
  1331. * sent to the netdev notifier chain.
  1332. *
  1333. * Calling this function on an active interface is a nop. On a failure
  1334. * a negative errno code is returned.
  1335. */
  1336. int dev_open(struct net_device *dev, struct netlink_ext_ack *extack)
  1337. {
  1338. int ret;
  1339. if (dev->flags & IFF_UP)
  1340. return 0;
  1341. ret = __dev_open(dev, extack);
  1342. if (ret < 0)
  1343. return ret;
  1344. rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
  1345. call_netdevice_notifiers(NETDEV_UP, dev);
  1346. return ret;
  1347. }
  1348. EXPORT_SYMBOL(dev_open);
  1349. static void __dev_close_many(struct list_head *head)
  1350. {
  1351. struct net_device *dev;
  1352. ASSERT_RTNL();
  1353. might_sleep();
  1354. list_for_each_entry(dev, head, close_list) {
  1355. /* Temporarily disable netpoll until the interface is down */
  1356. netpoll_poll_disable(dev);
  1357. call_netdevice_notifiers(NETDEV_GOING_DOWN, dev);
  1358. clear_bit(__LINK_STATE_START, &dev->state);
  1359. /* Synchronize to scheduled poll. We cannot touch poll list, it
  1360. * can be even on different cpu. So just clear netif_running().
  1361. *
  1362. * dev->stop() will invoke napi_disable() on all of it's
  1363. * napi_struct instances on this device.
  1364. */
  1365. smp_mb__after_atomic(); /* Commit netif_running(). */
  1366. }
  1367. dev_deactivate_many(head);
  1368. list_for_each_entry(dev, head, close_list) {
  1369. const struct net_device_ops *ops = dev->netdev_ops;
  1370. /*
  1371. * Call the device specific close. This cannot fail.
  1372. * Only if device is UP
  1373. *
  1374. * We allow it to be called even after a DETACH hot-plug
  1375. * event.
  1376. */
  1377. if (ops->ndo_stop)
  1378. ops->ndo_stop(dev);
  1379. dev->flags &= ~IFF_UP;
  1380. netpoll_poll_enable(dev);
  1381. }
  1382. }
  1383. static void __dev_close(struct net_device *dev)
  1384. {
  1385. LIST_HEAD(single);
  1386. list_add(&dev->close_list, &single);
  1387. __dev_close_many(&single);
  1388. list_del(&single);
  1389. }
  1390. void dev_close_many(struct list_head *head, bool unlink)
  1391. {
  1392. struct net_device *dev, *tmp;
  1393. /* Remove the devices that don't need to be closed */
  1394. list_for_each_entry_safe(dev, tmp, head, close_list)
  1395. if (!(dev->flags & IFF_UP))
  1396. list_del_init(&dev->close_list);
  1397. __dev_close_many(head);
  1398. list_for_each_entry_safe(dev, tmp, head, close_list) {
  1399. rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP | IFF_RUNNING, GFP_KERNEL, 0, NULL);
  1400. call_netdevice_notifiers(NETDEV_DOWN, dev);
  1401. if (unlink)
  1402. list_del_init(&dev->close_list);
  1403. }
  1404. }
  1405. EXPORT_SYMBOL(dev_close_many);
  1406. /**
  1407. * dev_close - shutdown an interface.
  1408. * @dev: device to shutdown
  1409. *
  1410. * This function moves an active device into down state. A
  1411. * %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
  1412. * is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
  1413. * chain.
  1414. */
  1415. void dev_close(struct net_device *dev)
  1416. {
  1417. if (dev->flags & IFF_UP) {
  1418. LIST_HEAD(single);
  1419. list_add(&dev->close_list, &single);
  1420. dev_close_many(&single, true);
  1421. list_del(&single);
  1422. }
  1423. }
  1424. EXPORT_SYMBOL(dev_close);
  1425. /**
  1426. * dev_disable_lro - disable Large Receive Offload on a device
  1427. * @dev: device
  1428. *
  1429. * Disable Large Receive Offload (LRO) on a net device. Must be
  1430. * called under RTNL. This is needed if received packets may be
  1431. * forwarded to another interface.
  1432. */
  1433. void dev_disable_lro(struct net_device *dev)
  1434. {
  1435. struct net_device *lower_dev;
  1436. struct list_head *iter;
  1437. dev->wanted_features &= ~NETIF_F_LRO;
  1438. netdev_update_features(dev);
  1439. if (unlikely(dev->features & NETIF_F_LRO))
  1440. netdev_WARN(dev, "failed to disable LRO!\n");
  1441. netdev_for_each_lower_dev(dev, lower_dev, iter)
  1442. dev_disable_lro(lower_dev);
  1443. }
  1444. EXPORT_SYMBOL(dev_disable_lro);
  1445. /**
  1446. * dev_disable_gro_hw - disable HW Generic Receive Offload on a device
  1447. * @dev: device
  1448. *
  1449. * Disable HW Generic Receive Offload (GRO_HW) on a net device. Must be
  1450. * called under RTNL. This is needed if Generic XDP is installed on
  1451. * the device.
  1452. */
  1453. static void dev_disable_gro_hw(struct net_device *dev)
  1454. {
  1455. dev->wanted_features &= ~NETIF_F_GRO_HW;
  1456. netdev_update_features(dev);
  1457. if (unlikely(dev->features & NETIF_F_GRO_HW))
  1458. netdev_WARN(dev, "failed to disable GRO_HW!\n");
  1459. }
  1460. const char *netdev_cmd_to_name(enum netdev_cmd cmd)
  1461. {
  1462. #define N(val) \
  1463. case NETDEV_##val: \
  1464. return "NETDEV_" __stringify(val);
  1465. switch (cmd) {
  1466. N(UP) N(DOWN) N(REBOOT) N(CHANGE) N(REGISTER) N(UNREGISTER)
  1467. N(CHANGEMTU) N(CHANGEADDR) N(GOING_DOWN) N(CHANGENAME) N(FEAT_CHANGE)
  1468. N(BONDING_FAILOVER) N(PRE_UP) N(PRE_TYPE_CHANGE) N(POST_TYPE_CHANGE)
  1469. N(POST_INIT) N(PRE_UNINIT) N(RELEASE) N(NOTIFY_PEERS) N(JOIN)
  1470. N(CHANGEUPPER) N(RESEND_IGMP) N(PRECHANGEMTU) N(CHANGEINFODATA)
  1471. N(BONDING_INFO) N(PRECHANGEUPPER) N(CHANGELOWERSTATE)
  1472. N(UDP_TUNNEL_PUSH_INFO) N(UDP_TUNNEL_DROP_INFO) N(CHANGE_TX_QUEUE_LEN)
  1473. N(CVLAN_FILTER_PUSH_INFO) N(CVLAN_FILTER_DROP_INFO)
  1474. N(SVLAN_FILTER_PUSH_INFO) N(SVLAN_FILTER_DROP_INFO)
  1475. N(PRE_CHANGEADDR) N(OFFLOAD_XSTATS_ENABLE) N(OFFLOAD_XSTATS_DISABLE)
  1476. N(OFFLOAD_XSTATS_REPORT_USED) N(OFFLOAD_XSTATS_REPORT_DELTA)
  1477. N(XDP_FEAT_CHANGE)
  1478. }
  1479. #undef N
  1480. return "UNKNOWN_NETDEV_EVENT";
  1481. }
  1482. EXPORT_SYMBOL_GPL(netdev_cmd_to_name);
  1483. static int call_netdevice_notifier(struct notifier_block *nb, unsigned long val,
  1484. struct net_device *dev)
  1485. {
  1486. struct netdev_notifier_info info = {
  1487. .dev = dev,
  1488. };
  1489. return nb->notifier_call(nb, val, &info);
  1490. }
  1491. static int call_netdevice_register_notifiers(struct notifier_block *nb,
  1492. struct net_device *dev)
  1493. {
  1494. int err;
  1495. err = call_netdevice_notifier(nb, NETDEV_REGISTER, dev);
  1496. err = notifier_to_errno(err);
  1497. if (err)
  1498. return err;
  1499. if (!(dev->flags & IFF_UP))
  1500. return 0;
  1501. call_netdevice_notifier(nb, NETDEV_UP, dev);
  1502. return 0;
  1503. }
  1504. static void call_netdevice_unregister_notifiers(struct notifier_block *nb,
  1505. struct net_device *dev)
  1506. {
  1507. if (dev->flags & IFF_UP) {
  1508. call_netdevice_notifier(nb, NETDEV_GOING_DOWN,
  1509. dev);
  1510. call_netdevice_notifier(nb, NETDEV_DOWN, dev);
  1511. }
  1512. call_netdevice_notifier(nb, NETDEV_UNREGISTER, dev);
  1513. }
  1514. static int call_netdevice_register_net_notifiers(struct notifier_block *nb,
  1515. struct net *net)
  1516. {
  1517. struct net_device *dev;
  1518. int err;
  1519. for_each_netdev(net, dev) {
  1520. err = call_netdevice_register_notifiers(nb, dev);
  1521. if (err)
  1522. goto rollback;
  1523. }
  1524. return 0;
  1525. rollback:
  1526. for_each_netdev_continue_reverse(net, dev)
  1527. call_netdevice_unregister_notifiers(nb, dev);
  1528. return err;
  1529. }
  1530. static void call_netdevice_unregister_net_notifiers(struct notifier_block *nb,
  1531. struct net *net)
  1532. {
  1533. struct net_device *dev;
  1534. for_each_netdev(net, dev)
  1535. call_netdevice_unregister_notifiers(nb, dev);
  1536. }
  1537. static int dev_boot_phase = 1;
  1538. /**
  1539. * register_netdevice_notifier - register a network notifier block
  1540. * @nb: notifier
  1541. *
  1542. * Register a notifier to be called when network device events occur.
  1543. * The notifier passed is linked into the kernel structures and must
  1544. * not be reused until it has been unregistered. A negative errno code
  1545. * is returned on a failure.
  1546. *
  1547. * When registered all registration and up events are replayed
  1548. * to the new notifier to allow device to have a race free
  1549. * view of the network device list.
  1550. */
  1551. int register_netdevice_notifier(struct notifier_block *nb)
  1552. {
  1553. struct net *net;
  1554. int err;
  1555. /* Close race with setup_net() and cleanup_net() */
  1556. down_write(&pernet_ops_rwsem);
  1557. rtnl_lock();
  1558. err = raw_notifier_chain_register(&netdev_chain, nb);
  1559. if (err)
  1560. goto unlock;
  1561. if (dev_boot_phase)
  1562. goto unlock;
  1563. for_each_net(net) {
  1564. err = call_netdevice_register_net_notifiers(nb, net);
  1565. if (err)
  1566. goto rollback;
  1567. }
  1568. unlock:
  1569. rtnl_unlock();
  1570. up_write(&pernet_ops_rwsem);
  1571. return err;
  1572. rollback:
  1573. for_each_net_continue_reverse(net)
  1574. call_netdevice_unregister_net_notifiers(nb, net);
  1575. raw_notifier_chain_unregister(&netdev_chain, nb);
  1576. goto unlock;
  1577. }
  1578. EXPORT_SYMBOL(register_netdevice_notifier);
  1579. /**
  1580. * unregister_netdevice_notifier - unregister a network notifier block
  1581. * @nb: notifier
  1582. *
  1583. * Unregister a notifier previously registered by
  1584. * register_netdevice_notifier(). The notifier is unlinked into the
  1585. * kernel structures and may then be reused. A negative errno code
  1586. * is returned on a failure.
  1587. *
  1588. * After unregistering unregister and down device events are synthesized
  1589. * for all devices on the device list to the removed notifier to remove
  1590. * the need for special case cleanup code.
  1591. */
  1592. int unregister_netdevice_notifier(struct notifier_block *nb)
  1593. {
  1594. struct net *net;
  1595. int err;
  1596. /* Close race with setup_net() and cleanup_net() */
  1597. down_write(&pernet_ops_rwsem);
  1598. rtnl_lock();
  1599. err = raw_notifier_chain_unregister(&netdev_chain, nb);
  1600. if (err)
  1601. goto unlock;
  1602. for_each_net(net)
  1603. call_netdevice_unregister_net_notifiers(nb, net);
  1604. unlock:
  1605. rtnl_unlock();
  1606. up_write(&pernet_ops_rwsem);
  1607. return err;
  1608. }
  1609. EXPORT_SYMBOL(unregister_netdevice_notifier);
  1610. static int __register_netdevice_notifier_net(struct net *net,
  1611. struct notifier_block *nb,
  1612. bool ignore_call_fail)
  1613. {
  1614. int err;
  1615. err = raw_notifier_chain_register(&net->netdev_chain, nb);
  1616. if (err)
  1617. return err;
  1618. if (dev_boot_phase)
  1619. return 0;
  1620. err = call_netdevice_register_net_notifiers(nb, net);
  1621. if (err && !ignore_call_fail)
  1622. goto chain_unregister;
  1623. return 0;
  1624. chain_unregister:
  1625. raw_notifier_chain_unregister(&net->netdev_chain, nb);
  1626. return err;
  1627. }
  1628. static int __unregister_netdevice_notifier_net(struct net *net,
  1629. struct notifier_block *nb)
  1630. {
  1631. int err;
  1632. err = raw_notifier_chain_unregister(&net->netdev_chain, nb);
  1633. if (err)
  1634. return err;
  1635. call_netdevice_unregister_net_notifiers(nb, net);
  1636. return 0;
  1637. }
  1638. /**
  1639. * register_netdevice_notifier_net - register a per-netns network notifier block
  1640. * @net: network namespace
  1641. * @nb: notifier
  1642. *
  1643. * Register a notifier to be called when network device events occur.
  1644. * The notifier passed is linked into the kernel structures and must
  1645. * not be reused until it has been unregistered. A negative errno code
  1646. * is returned on a failure.
  1647. *
  1648. * When registered all registration and up events are replayed
  1649. * to the new notifier to allow device to have a race free
  1650. * view of the network device list.
  1651. */
  1652. int register_netdevice_notifier_net(struct net *net, struct notifier_block *nb)
  1653. {
  1654. int err;
  1655. rtnl_lock();
  1656. err = __register_netdevice_notifier_net(net, nb, false);
  1657. rtnl_unlock();
  1658. return err;
  1659. }
  1660. EXPORT_SYMBOL(register_netdevice_notifier_net);
  1661. /**
  1662. * unregister_netdevice_notifier_net - unregister a per-netns
  1663. * network notifier block
  1664. * @net: network namespace
  1665. * @nb: notifier
  1666. *
  1667. * Unregister a notifier previously registered by
  1668. * register_netdevice_notifier_net(). The notifier is unlinked from the
  1669. * kernel structures and may then be reused. A negative errno code
  1670. * is returned on a failure.
  1671. *
  1672. * After unregistering unregister and down device events are synthesized
  1673. * for all devices on the device list to the removed notifier to remove
  1674. * the need for special case cleanup code.
  1675. */
  1676. int unregister_netdevice_notifier_net(struct net *net,
  1677. struct notifier_block *nb)
  1678. {
  1679. int err;
  1680. rtnl_lock();
  1681. err = __unregister_netdevice_notifier_net(net, nb);
  1682. rtnl_unlock();
  1683. return err;
  1684. }
  1685. EXPORT_SYMBOL(unregister_netdevice_notifier_net);
  1686. static void __move_netdevice_notifier_net(struct net *src_net,
  1687. struct net *dst_net,
  1688. struct notifier_block *nb)
  1689. {
  1690. __unregister_netdevice_notifier_net(src_net, nb);
  1691. __register_netdevice_notifier_net(dst_net, nb, true);
  1692. }
  1693. int register_netdevice_notifier_dev_net(struct net_device *dev,
  1694. struct notifier_block *nb,
  1695. struct netdev_net_notifier *nn)
  1696. {
  1697. int err;
  1698. rtnl_lock();
  1699. err = __register_netdevice_notifier_net(dev_net(dev), nb, false);
  1700. if (!err) {
  1701. nn->nb = nb;
  1702. list_add(&nn->list, &dev->net_notifier_list);
  1703. }
  1704. rtnl_unlock();
  1705. return err;
  1706. }
  1707. EXPORT_SYMBOL(register_netdevice_notifier_dev_net);
  1708. int unregister_netdevice_notifier_dev_net(struct net_device *dev,
  1709. struct notifier_block *nb,
  1710. struct netdev_net_notifier *nn)
  1711. {
  1712. int err;
  1713. rtnl_lock();
  1714. list_del(&nn->list);
  1715. err = __unregister_netdevice_notifier_net(dev_net(dev), nb);
  1716. rtnl_unlock();
  1717. return err;
  1718. }
  1719. EXPORT_SYMBOL(unregister_netdevice_notifier_dev_net);
  1720. static void move_netdevice_notifiers_dev_net(struct net_device *dev,
  1721. struct net *net)
  1722. {
  1723. struct netdev_net_notifier *nn;
  1724. list_for_each_entry(nn, &dev->net_notifier_list, list)
  1725. __move_netdevice_notifier_net(dev_net(dev), net, nn->nb);
  1726. }
  1727. /**
  1728. * call_netdevice_notifiers_info - call all network notifier blocks
  1729. * @val: value passed unmodified to notifier function
  1730. * @info: notifier information data
  1731. *
  1732. * Call all network notifier blocks. Parameters and return value
  1733. * are as for raw_notifier_call_chain().
  1734. */
  1735. int call_netdevice_notifiers_info(unsigned long val,
  1736. struct netdev_notifier_info *info)
  1737. {
  1738. struct net *net = dev_net(info->dev);
  1739. int ret;
  1740. ASSERT_RTNL();
  1741. /* Run per-netns notifier block chain first, then run the global one.
  1742. * Hopefully, one day, the global one is going to be removed after
  1743. * all notifier block registrators get converted to be per-netns.
  1744. */
  1745. ret = raw_notifier_call_chain(&net->netdev_chain, val, info);
  1746. if (ret & NOTIFY_STOP_MASK)
  1747. return ret;
  1748. return raw_notifier_call_chain(&netdev_chain, val, info);
  1749. }
  1750. /**
  1751. * call_netdevice_notifiers_info_robust - call per-netns notifier blocks
  1752. * for and rollback on error
  1753. * @val_up: value passed unmodified to notifier function
  1754. * @val_down: value passed unmodified to the notifier function when
  1755. * recovering from an error on @val_up
  1756. * @info: notifier information data
  1757. *
  1758. * Call all per-netns network notifier blocks, but not notifier blocks on
  1759. * the global notifier chain. Parameters and return value are as for
  1760. * raw_notifier_call_chain_robust().
  1761. */
  1762. static int
  1763. call_netdevice_notifiers_info_robust(unsigned long val_up,
  1764. unsigned long val_down,
  1765. struct netdev_notifier_info *info)
  1766. {
  1767. struct net *net = dev_net(info->dev);
  1768. ASSERT_RTNL();
  1769. return raw_notifier_call_chain_robust(&net->netdev_chain,
  1770. val_up, val_down, info);
  1771. }
  1772. static int call_netdevice_notifiers_extack(unsigned long val,
  1773. struct net_device *dev,
  1774. struct netlink_ext_ack *extack)
  1775. {
  1776. struct netdev_notifier_info info = {
  1777. .dev = dev,
  1778. .extack = extack,
  1779. };
  1780. return call_netdevice_notifiers_info(val, &info);
  1781. }
  1782. /**
  1783. * call_netdevice_notifiers - call all network notifier blocks
  1784. * @val: value passed unmodified to notifier function
  1785. * @dev: net_device pointer passed unmodified to notifier function
  1786. *
  1787. * Call all network notifier blocks. Parameters and return value
  1788. * are as for raw_notifier_call_chain().
  1789. */
  1790. int call_netdevice_notifiers(unsigned long val, struct net_device *dev)
  1791. {
  1792. return call_netdevice_notifiers_extack(val, dev, NULL);
  1793. }
  1794. EXPORT_SYMBOL(call_netdevice_notifiers);
  1795. /**
  1796. * call_netdevice_notifiers_mtu - call all network notifier blocks
  1797. * @val: value passed unmodified to notifier function
  1798. * @dev: net_device pointer passed unmodified to notifier function
  1799. * @arg: additional u32 argument passed to the notifier function
  1800. *
  1801. * Call all network notifier blocks. Parameters and return value
  1802. * are as for raw_notifier_call_chain().
  1803. */
  1804. static int call_netdevice_notifiers_mtu(unsigned long val,
  1805. struct net_device *dev, u32 arg)
  1806. {
  1807. struct netdev_notifier_info_ext info = {
  1808. .info.dev = dev,
  1809. .ext.mtu = arg,
  1810. };
  1811. BUILD_BUG_ON(offsetof(struct netdev_notifier_info_ext, info) != 0);
  1812. return call_netdevice_notifiers_info(val, &info.info);
  1813. }
  1814. #ifdef CONFIG_NET_INGRESS
  1815. static DEFINE_STATIC_KEY_FALSE(ingress_needed_key);
  1816. void net_inc_ingress_queue(void)
  1817. {
  1818. static_branch_inc(&ingress_needed_key);
  1819. }
  1820. EXPORT_SYMBOL_GPL(net_inc_ingress_queue);
  1821. void net_dec_ingress_queue(void)
  1822. {
  1823. static_branch_dec(&ingress_needed_key);
  1824. }
  1825. EXPORT_SYMBOL_GPL(net_dec_ingress_queue);
  1826. #endif
  1827. #ifdef CONFIG_NET_EGRESS
  1828. static DEFINE_STATIC_KEY_FALSE(egress_needed_key);
  1829. void net_inc_egress_queue(void)
  1830. {
  1831. static_branch_inc(&egress_needed_key);
  1832. }
  1833. EXPORT_SYMBOL_GPL(net_inc_egress_queue);
  1834. void net_dec_egress_queue(void)
  1835. {
  1836. static_branch_dec(&egress_needed_key);
  1837. }
  1838. EXPORT_SYMBOL_GPL(net_dec_egress_queue);
  1839. #endif
  1840. #ifdef CONFIG_NET_CLS_ACT
  1841. DEFINE_STATIC_KEY_FALSE(tcf_sw_enabled_key);
  1842. EXPORT_SYMBOL(tcf_sw_enabled_key);
  1843. #endif
  1844. DEFINE_STATIC_KEY_FALSE(netstamp_needed_key);
  1845. EXPORT_SYMBOL(netstamp_needed_key);
  1846. #ifdef CONFIG_JUMP_LABEL
  1847. static atomic_t netstamp_needed_deferred;
  1848. static atomic_t netstamp_wanted;
  1849. static void netstamp_clear(struct work_struct *work)
  1850. {
  1851. int deferred = atomic_xchg(&netstamp_needed_deferred, 0);
  1852. int wanted;
  1853. wanted = atomic_add_return(deferred, &netstamp_wanted);
  1854. if (wanted > 0)
  1855. static_branch_enable(&netstamp_needed_key);
  1856. else
  1857. static_branch_disable(&netstamp_needed_key);
  1858. }
  1859. static DECLARE_WORK(netstamp_work, netstamp_clear);
  1860. #endif
  1861. void net_enable_timestamp(void)
  1862. {
  1863. #ifdef CONFIG_JUMP_LABEL
  1864. int wanted = atomic_read(&netstamp_wanted);
  1865. while (wanted > 0) {
  1866. if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted + 1))
  1867. return;
  1868. }
  1869. atomic_inc(&netstamp_needed_deferred);
  1870. schedule_work(&netstamp_work);
  1871. #else
  1872. static_branch_inc(&netstamp_needed_key);
  1873. #endif
  1874. }
  1875. EXPORT_SYMBOL(net_enable_timestamp);
  1876. void net_disable_timestamp(void)
  1877. {
  1878. #ifdef CONFIG_JUMP_LABEL
  1879. int wanted = atomic_read(&netstamp_wanted);
  1880. while (wanted > 1) {
  1881. if (atomic_try_cmpxchg(&netstamp_wanted, &wanted, wanted - 1))
  1882. return;
  1883. }
  1884. atomic_dec(&netstamp_needed_deferred);
  1885. schedule_work(&netstamp_work);
  1886. #else
  1887. static_branch_dec(&netstamp_needed_key);
  1888. #endif
  1889. }
  1890. EXPORT_SYMBOL(net_disable_timestamp);
  1891. static inline void net_timestamp_set(struct sk_buff *skb)
  1892. {
  1893. skb->tstamp = 0;
  1894. skb->tstamp_type = SKB_CLOCK_REALTIME;
  1895. if (static_branch_unlikely(&netstamp_needed_key))
  1896. skb->tstamp = ktime_get_real();
  1897. }
  1898. #define net_timestamp_check(COND, SKB) \
  1899. if (static_branch_unlikely(&netstamp_needed_key)) { \
  1900. if ((COND) && !(SKB)->tstamp) \
  1901. (SKB)->tstamp = ktime_get_real(); \
  1902. } \
  1903. bool is_skb_forwardable(const struct net_device *dev, const struct sk_buff *skb)
  1904. {
  1905. return __is_skb_forwardable(dev, skb, true);
  1906. }
  1907. EXPORT_SYMBOL_GPL(is_skb_forwardable);
  1908. static int __dev_forward_skb2(struct net_device *dev, struct sk_buff *skb,
  1909. bool check_mtu)
  1910. {
  1911. int ret = ____dev_forward_skb(dev, skb, check_mtu);
  1912. if (likely(!ret)) {
  1913. skb->protocol = eth_type_trans(skb, dev);
  1914. skb_postpull_rcsum(skb, eth_hdr(skb), ETH_HLEN);
  1915. }
  1916. return ret;
  1917. }
  1918. int __dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
  1919. {
  1920. return __dev_forward_skb2(dev, skb, true);
  1921. }
  1922. EXPORT_SYMBOL_GPL(__dev_forward_skb);
  1923. /**
  1924. * dev_forward_skb - loopback an skb to another netif
  1925. *
  1926. * @dev: destination network device
  1927. * @skb: buffer to forward
  1928. *
  1929. * return values:
  1930. * NET_RX_SUCCESS (no congestion)
  1931. * NET_RX_DROP (packet was dropped, but freed)
  1932. *
  1933. * dev_forward_skb can be used for injecting an skb from the
  1934. * start_xmit function of one device into the receive queue
  1935. * of another device.
  1936. *
  1937. * The receiving device may be in another namespace, so
  1938. * we have to clear all information in the skb that could
  1939. * impact namespace isolation.
  1940. */
  1941. int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
  1942. {
  1943. return __dev_forward_skb(dev, skb) ?: netif_rx_internal(skb);
  1944. }
  1945. EXPORT_SYMBOL_GPL(dev_forward_skb);
  1946. int dev_forward_skb_nomtu(struct net_device *dev, struct sk_buff *skb)
  1947. {
  1948. return __dev_forward_skb2(dev, skb, false) ?: netif_rx_internal(skb);
  1949. }
  1950. static inline int deliver_skb(struct sk_buff *skb,
  1951. struct packet_type *pt_prev,
  1952. struct net_device *orig_dev)
  1953. {
  1954. if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
  1955. return -ENOMEM;
  1956. refcount_inc(&skb->users);
  1957. return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
  1958. }
  1959. static inline void deliver_ptype_list_skb(struct sk_buff *skb,
  1960. struct packet_type **pt,
  1961. struct net_device *orig_dev,
  1962. __be16 type,
  1963. struct list_head *ptype_list)
  1964. {
  1965. struct packet_type *ptype, *pt_prev = *pt;
  1966. list_for_each_entry_rcu(ptype, ptype_list, list) {
  1967. if (ptype->type != type)
  1968. continue;
  1969. if (pt_prev)
  1970. deliver_skb(skb, pt_prev, orig_dev);
  1971. pt_prev = ptype;
  1972. }
  1973. *pt = pt_prev;
  1974. }
  1975. static inline bool skb_loop_sk(struct packet_type *ptype, struct sk_buff *skb)
  1976. {
  1977. if (!ptype->af_packet_priv || !skb->sk)
  1978. return false;
  1979. if (ptype->id_match)
  1980. return ptype->id_match(ptype, skb->sk);
  1981. else if ((struct sock *)ptype->af_packet_priv == skb->sk)
  1982. return true;
  1983. return false;
  1984. }
  1985. /**
  1986. * dev_nit_active - return true if any network interface taps are in use
  1987. *
  1988. * @dev: network device to check for the presence of taps
  1989. */
  1990. bool dev_nit_active(struct net_device *dev)
  1991. {
  1992. return !list_empty(&net_hotdata.ptype_all) ||
  1993. !list_empty(&dev->ptype_all);
  1994. }
  1995. EXPORT_SYMBOL_GPL(dev_nit_active);
  1996. /*
  1997. * Support routine. Sends outgoing frames to any network
  1998. * taps currently in use.
  1999. */
  2000. void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
  2001. {
  2002. struct list_head *ptype_list = &net_hotdata.ptype_all;
  2003. struct packet_type *ptype, *pt_prev = NULL;
  2004. struct sk_buff *skb2 = NULL;
  2005. rcu_read_lock();
  2006. again:
  2007. list_for_each_entry_rcu(ptype, ptype_list, list) {
  2008. if (READ_ONCE(ptype->ignore_outgoing))
  2009. continue;
  2010. /* Never send packets back to the socket
  2011. * they originated from - MvS (miquels@drinkel.ow.org)
  2012. */
  2013. if (skb_loop_sk(ptype, skb))
  2014. continue;
  2015. if (pt_prev) {
  2016. deliver_skb(skb2, pt_prev, skb->dev);
  2017. pt_prev = ptype;
  2018. continue;
  2019. }
  2020. /* need to clone skb, done only once */
  2021. skb2 = skb_clone(skb, GFP_ATOMIC);
  2022. if (!skb2)
  2023. goto out_unlock;
  2024. net_timestamp_set(skb2);
  2025. /* skb->nh should be correctly
  2026. * set by sender, so that the second statement is
  2027. * just protection against buggy protocols.
  2028. */
  2029. skb_reset_mac_header(skb2);
  2030. if (skb_network_header(skb2) < skb2->data ||
  2031. skb_network_header(skb2) > skb_tail_pointer(skb2)) {
  2032. net_crit_ratelimited("protocol %04x is buggy, dev %s\n",
  2033. ntohs(skb2->protocol),
  2034. dev->name);
  2035. skb_reset_network_header(skb2);
  2036. }
  2037. skb2->transport_header = skb2->network_header;
  2038. skb2->pkt_type = PACKET_OUTGOING;
  2039. pt_prev = ptype;
  2040. }
  2041. if (ptype_list == &net_hotdata.ptype_all) {
  2042. ptype_list = &dev->ptype_all;
  2043. goto again;
  2044. }
  2045. out_unlock:
  2046. if (pt_prev) {
  2047. if (!skb_orphan_frags_rx(skb2, GFP_ATOMIC))
  2048. pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
  2049. else
  2050. kfree_skb(skb2);
  2051. }
  2052. rcu_read_unlock();
  2053. }
  2054. EXPORT_SYMBOL_GPL(dev_queue_xmit_nit);
  2055. /**
  2056. * netif_setup_tc - Handle tc mappings on real_num_tx_queues change
  2057. * @dev: Network device
  2058. * @txq: number of queues available
  2059. *
  2060. * If real_num_tx_queues is changed the tc mappings may no longer be
  2061. * valid. To resolve this verify the tc mapping remains valid and if
  2062. * not NULL the mapping. With no priorities mapping to this
  2063. * offset/count pair it will no longer be used. In the worst case TC0
  2064. * is invalid nothing can be done so disable priority mappings. If is
  2065. * expected that drivers will fix this mapping if they can before
  2066. * calling netif_set_real_num_tx_queues.
  2067. */
  2068. static void netif_setup_tc(struct net_device *dev, unsigned int txq)
  2069. {
  2070. int i;
  2071. struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
  2072. /* If TC0 is invalidated disable TC mapping */
  2073. if (tc->offset + tc->count > txq) {
  2074. netdev_warn(dev, "Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
  2075. dev->num_tc = 0;
  2076. return;
  2077. }
  2078. /* Invalidated prio to tc mappings set to TC0 */
  2079. for (i = 1; i < TC_BITMASK + 1; i++) {
  2080. int q = netdev_get_prio_tc_map(dev, i);
  2081. tc = &dev->tc_to_txq[q];
  2082. if (tc->offset + tc->count > txq) {
  2083. netdev_warn(dev, "Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
  2084. i, q);
  2085. netdev_set_prio_tc_map(dev, i, 0);
  2086. }
  2087. }
  2088. }
  2089. int netdev_txq_to_tc(struct net_device *dev, unsigned int txq)
  2090. {
  2091. if (dev->num_tc) {
  2092. struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
  2093. int i;
  2094. /* walk through the TCs and see if it falls into any of them */
  2095. for (i = 0; i < TC_MAX_QUEUE; i++, tc++) {
  2096. if ((txq - tc->offset) < tc->count)
  2097. return i;
  2098. }
  2099. /* didn't find it, just return -1 to indicate no match */
  2100. return -1;
  2101. }
  2102. return 0;
  2103. }
  2104. EXPORT_SYMBOL(netdev_txq_to_tc);
  2105. #ifdef CONFIG_XPS
  2106. static struct static_key xps_needed __read_mostly;
  2107. static struct static_key xps_rxqs_needed __read_mostly;
  2108. static DEFINE_MUTEX(xps_map_mutex);
  2109. #define xmap_dereference(P) \
  2110. rcu_dereference_protected((P), lockdep_is_held(&xps_map_mutex))
  2111. static bool remove_xps_queue(struct xps_dev_maps *dev_maps,
  2112. struct xps_dev_maps *old_maps, int tci, u16 index)
  2113. {
  2114. struct xps_map *map = NULL;
  2115. int pos;
  2116. map = xmap_dereference(dev_maps->attr_map[tci]);
  2117. if (!map)
  2118. return false;
  2119. for (pos = map->len; pos--;) {
  2120. if (map->queues[pos] != index)
  2121. continue;
  2122. if (map->len > 1) {
  2123. map->queues[pos] = map->queues[--map->len];
  2124. break;
  2125. }
  2126. if (old_maps)
  2127. RCU_INIT_POINTER(old_maps->attr_map[tci], NULL);
  2128. RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
  2129. kfree_rcu(map, rcu);
  2130. return false;
  2131. }
  2132. return true;
  2133. }
  2134. static bool remove_xps_queue_cpu(struct net_device *dev,
  2135. struct xps_dev_maps *dev_maps,
  2136. int cpu, u16 offset, u16 count)
  2137. {
  2138. int num_tc = dev_maps->num_tc;
  2139. bool active = false;
  2140. int tci;
  2141. for (tci = cpu * num_tc; num_tc--; tci++) {
  2142. int i, j;
  2143. for (i = count, j = offset; i--; j++) {
  2144. if (!remove_xps_queue(dev_maps, NULL, tci, j))
  2145. break;
  2146. }
  2147. active |= i < 0;
  2148. }
  2149. return active;
  2150. }
  2151. static void reset_xps_maps(struct net_device *dev,
  2152. struct xps_dev_maps *dev_maps,
  2153. enum xps_map_type type)
  2154. {
  2155. static_key_slow_dec_cpuslocked(&xps_needed);
  2156. if (type == XPS_RXQS)
  2157. static_key_slow_dec_cpuslocked(&xps_rxqs_needed);
  2158. RCU_INIT_POINTER(dev->xps_maps[type], NULL);
  2159. kfree_rcu(dev_maps, rcu);
  2160. }
  2161. static void clean_xps_maps(struct net_device *dev, enum xps_map_type type,
  2162. u16 offset, u16 count)
  2163. {
  2164. struct xps_dev_maps *dev_maps;
  2165. bool active = false;
  2166. int i, j;
  2167. dev_maps = xmap_dereference(dev->xps_maps[type]);
  2168. if (!dev_maps)
  2169. return;
  2170. for (j = 0; j < dev_maps->nr_ids; j++)
  2171. active |= remove_xps_queue_cpu(dev, dev_maps, j, offset, count);
  2172. if (!active)
  2173. reset_xps_maps(dev, dev_maps, type);
  2174. if (type == XPS_CPUS) {
  2175. for (i = offset + (count - 1); count--; i--)
  2176. netdev_queue_numa_node_write(
  2177. netdev_get_tx_queue(dev, i), NUMA_NO_NODE);
  2178. }
  2179. }
  2180. static void netif_reset_xps_queues(struct net_device *dev, u16 offset,
  2181. u16 count)
  2182. {
  2183. if (!static_key_false(&xps_needed))
  2184. return;
  2185. cpus_read_lock();
  2186. mutex_lock(&xps_map_mutex);
  2187. if (static_key_false(&xps_rxqs_needed))
  2188. clean_xps_maps(dev, XPS_RXQS, offset, count);
  2189. clean_xps_maps(dev, XPS_CPUS, offset, count);
  2190. mutex_unlock(&xps_map_mutex);
  2191. cpus_read_unlock();
  2192. }
  2193. static void netif_reset_xps_queues_gt(struct net_device *dev, u16 index)
  2194. {
  2195. netif_reset_xps_queues(dev, index, dev->num_tx_queues - index);
  2196. }
  2197. static struct xps_map *expand_xps_map(struct xps_map *map, int attr_index,
  2198. u16 index, bool is_rxqs_map)
  2199. {
  2200. struct xps_map *new_map;
  2201. int alloc_len = XPS_MIN_MAP_ALLOC;
  2202. int i, pos;
  2203. for (pos = 0; map && pos < map->len; pos++) {
  2204. if (map->queues[pos] != index)
  2205. continue;
  2206. return map;
  2207. }
  2208. /* Need to add tx-queue to this CPU's/rx-queue's existing map */
  2209. if (map) {
  2210. if (pos < map->alloc_len)
  2211. return map;
  2212. alloc_len = map->alloc_len * 2;
  2213. }
  2214. /* Need to allocate new map to store tx-queue on this CPU's/rx-queue's
  2215. * map
  2216. */
  2217. if (is_rxqs_map)
  2218. new_map = kzalloc(XPS_MAP_SIZE(alloc_len), GFP_KERNEL);
  2219. else
  2220. new_map = kzalloc_node(XPS_MAP_SIZE(alloc_len), GFP_KERNEL,
  2221. cpu_to_node(attr_index));
  2222. if (!new_map)
  2223. return NULL;
  2224. for (i = 0; i < pos; i++)
  2225. new_map->queues[i] = map->queues[i];
  2226. new_map->alloc_len = alloc_len;
  2227. new_map->len = pos;
  2228. return new_map;
  2229. }
  2230. /* Copy xps maps at a given index */
  2231. static void xps_copy_dev_maps(struct xps_dev_maps *dev_maps,
  2232. struct xps_dev_maps *new_dev_maps, int index,
  2233. int tc, bool skip_tc)
  2234. {
  2235. int i, tci = index * dev_maps->num_tc;
  2236. struct xps_map *map;
  2237. /* copy maps belonging to foreign traffic classes */
  2238. for (i = 0; i < dev_maps->num_tc; i++, tci++) {
  2239. if (i == tc && skip_tc)
  2240. continue;
  2241. /* fill in the new device map from the old device map */
  2242. map = xmap_dereference(dev_maps->attr_map[tci]);
  2243. RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
  2244. }
  2245. }
  2246. /* Must be called under cpus_read_lock */
  2247. int __netif_set_xps_queue(struct net_device *dev, const unsigned long *mask,
  2248. u16 index, enum xps_map_type type)
  2249. {
  2250. struct xps_dev_maps *dev_maps, *new_dev_maps = NULL, *old_dev_maps = NULL;
  2251. const unsigned long *online_mask = NULL;
  2252. bool active = false, copy = false;
  2253. int i, j, tci, numa_node_id = -2;
  2254. int maps_sz, num_tc = 1, tc = 0;
  2255. struct xps_map *map, *new_map;
  2256. unsigned int nr_ids;
  2257. WARN_ON_ONCE(index >= dev->num_tx_queues);
  2258. if (dev->num_tc) {
  2259. /* Do not allow XPS on subordinate device directly */
  2260. num_tc = dev->num_tc;
  2261. if (num_tc < 0)
  2262. return -EINVAL;
  2263. /* If queue belongs to subordinate dev use its map */
  2264. dev = netdev_get_tx_queue(dev, index)->sb_dev ? : dev;
  2265. tc = netdev_txq_to_tc(dev, index);
  2266. if (tc < 0)
  2267. return -EINVAL;
  2268. }
  2269. mutex_lock(&xps_map_mutex);
  2270. dev_maps = xmap_dereference(dev->xps_maps[type]);
  2271. if (type == XPS_RXQS) {
  2272. maps_sz = XPS_RXQ_DEV_MAPS_SIZE(num_tc, dev->num_rx_queues);
  2273. nr_ids = dev->num_rx_queues;
  2274. } else {
  2275. maps_sz = XPS_CPU_DEV_MAPS_SIZE(num_tc);
  2276. if (num_possible_cpus() > 1)
  2277. online_mask = cpumask_bits(cpu_online_mask);
  2278. nr_ids = nr_cpu_ids;
  2279. }
  2280. if (maps_sz < L1_CACHE_BYTES)
  2281. maps_sz = L1_CACHE_BYTES;
  2282. /* The old dev_maps could be larger or smaller than the one we're
  2283. * setting up now, as dev->num_tc or nr_ids could have been updated in
  2284. * between. We could try to be smart, but let's be safe instead and only
  2285. * copy foreign traffic classes if the two map sizes match.
  2286. */
  2287. if (dev_maps &&
  2288. dev_maps->num_tc == num_tc && dev_maps->nr_ids == nr_ids)
  2289. copy = true;
  2290. /* allocate memory for queue storage */
  2291. for (j = -1; j = netif_attrmask_next_and(j, online_mask, mask, nr_ids),
  2292. j < nr_ids;) {
  2293. if (!new_dev_maps) {
  2294. new_dev_maps = kzalloc(maps_sz, GFP_KERNEL);
  2295. if (!new_dev_maps) {
  2296. mutex_unlock(&xps_map_mutex);
  2297. return -ENOMEM;
  2298. }
  2299. new_dev_maps->nr_ids = nr_ids;
  2300. new_dev_maps->num_tc = num_tc;
  2301. }
  2302. tci = j * num_tc + tc;
  2303. map = copy ? xmap_dereference(dev_maps->attr_map[tci]) : NULL;
  2304. map = expand_xps_map(map, j, index, type == XPS_RXQS);
  2305. if (!map)
  2306. goto error;
  2307. RCU_INIT_POINTER(new_dev_maps->attr_map[tci], map);
  2308. }
  2309. if (!new_dev_maps)
  2310. goto out_no_new_maps;
  2311. if (!dev_maps) {
  2312. /* Increment static keys at most once per type */
  2313. static_key_slow_inc_cpuslocked(&xps_needed);
  2314. if (type == XPS_RXQS)
  2315. static_key_slow_inc_cpuslocked(&xps_rxqs_needed);
  2316. }
  2317. for (j = 0; j < nr_ids; j++) {
  2318. bool skip_tc = false;
  2319. tci = j * num_tc + tc;
  2320. if (netif_attr_test_mask(j, mask, nr_ids) &&
  2321. netif_attr_test_online(j, online_mask, nr_ids)) {
  2322. /* add tx-queue to CPU/rx-queue maps */
  2323. int pos = 0;
  2324. skip_tc = true;
  2325. map = xmap_dereference(new_dev_maps->attr_map[tci]);
  2326. while ((pos < map->len) && (map->queues[pos] != index))
  2327. pos++;
  2328. if (pos == map->len)
  2329. map->queues[map->len++] = index;
  2330. #ifdef CONFIG_NUMA
  2331. if (type == XPS_CPUS) {
  2332. if (numa_node_id == -2)
  2333. numa_node_id = cpu_to_node(j);
  2334. else if (numa_node_id != cpu_to_node(j))
  2335. numa_node_id = -1;
  2336. }
  2337. #endif
  2338. }
  2339. if (copy)
  2340. xps_copy_dev_maps(dev_maps, new_dev_maps, j, tc,
  2341. skip_tc);
  2342. }
  2343. rcu_assign_pointer(dev->xps_maps[type], new_dev_maps);
  2344. /* Cleanup old maps */
  2345. if (!dev_maps)
  2346. goto out_no_old_maps;
  2347. for (j = 0; j < dev_maps->nr_ids; j++) {
  2348. for (i = num_tc, tci = j * dev_maps->num_tc; i--; tci++) {
  2349. map = xmap_dereference(dev_maps->attr_map[tci]);
  2350. if (!map)
  2351. continue;
  2352. if (copy) {
  2353. new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
  2354. if (map == new_map)
  2355. continue;
  2356. }
  2357. RCU_INIT_POINTER(dev_maps->attr_map[tci], NULL);
  2358. kfree_rcu(map, rcu);
  2359. }
  2360. }
  2361. old_dev_maps = dev_maps;
  2362. out_no_old_maps:
  2363. dev_maps = new_dev_maps;
  2364. active = true;
  2365. out_no_new_maps:
  2366. if (type == XPS_CPUS)
  2367. /* update Tx queue numa node */
  2368. netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index),
  2369. (numa_node_id >= 0) ?
  2370. numa_node_id : NUMA_NO_NODE);
  2371. if (!dev_maps)
  2372. goto out_no_maps;
  2373. /* removes tx-queue from unused CPUs/rx-queues */
  2374. for (j = 0; j < dev_maps->nr_ids; j++) {
  2375. tci = j * dev_maps->num_tc;
  2376. for (i = 0; i < dev_maps->num_tc; i++, tci++) {
  2377. if (i == tc &&
  2378. netif_attr_test_mask(j, mask, dev_maps->nr_ids) &&
  2379. netif_attr_test_online(j, online_mask, dev_maps->nr_ids))
  2380. continue;
  2381. active |= remove_xps_queue(dev_maps,
  2382. copy ? old_dev_maps : NULL,
  2383. tci, index);
  2384. }
  2385. }
  2386. if (old_dev_maps)
  2387. kfree_rcu(old_dev_maps, rcu);
  2388. /* free map if not active */
  2389. if (!active)
  2390. reset_xps_maps(dev, dev_maps, type);
  2391. out_no_maps:
  2392. mutex_unlock(&xps_map_mutex);
  2393. return 0;
  2394. error:
  2395. /* remove any maps that we added */
  2396. for (j = 0; j < nr_ids; j++) {
  2397. for (i = num_tc, tci = j * num_tc; i--; tci++) {
  2398. new_map = xmap_dereference(new_dev_maps->attr_map[tci]);
  2399. map = copy ?
  2400. xmap_dereference(dev_maps->attr_map[tci]) :
  2401. NULL;
  2402. if (new_map && new_map != map)
  2403. kfree(new_map);
  2404. }
  2405. }
  2406. mutex_unlock(&xps_map_mutex);
  2407. kfree(new_dev_maps);
  2408. return -ENOMEM;
  2409. }
  2410. EXPORT_SYMBOL_GPL(__netif_set_xps_queue);
  2411. int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask,
  2412. u16 index)
  2413. {
  2414. int ret;
  2415. cpus_read_lock();
  2416. ret = __netif_set_xps_queue(dev, cpumask_bits(mask), index, XPS_CPUS);
  2417. cpus_read_unlock();
  2418. return ret;
  2419. }
  2420. EXPORT_SYMBOL(netif_set_xps_queue);
  2421. #endif
  2422. static void netdev_unbind_all_sb_channels(struct net_device *dev)
  2423. {
  2424. struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
  2425. /* Unbind any subordinate channels */
  2426. while (txq-- != &dev->_tx[0]) {
  2427. if (txq->sb_dev)
  2428. netdev_unbind_sb_channel(dev, txq->sb_dev);
  2429. }
  2430. }
  2431. void netdev_reset_tc(struct net_device *dev)
  2432. {
  2433. #ifdef CONFIG_XPS
  2434. netif_reset_xps_queues_gt(dev, 0);
  2435. #endif
  2436. netdev_unbind_all_sb_channels(dev);
  2437. /* Reset TC configuration of device */
  2438. dev->num_tc = 0;
  2439. memset(dev->tc_to_txq, 0, sizeof(dev->tc_to_txq));
  2440. memset(dev->prio_tc_map, 0, sizeof(dev->prio_tc_map));
  2441. }
  2442. EXPORT_SYMBOL(netdev_reset_tc);
  2443. int netdev_set_tc_queue(struct net_device *dev, u8 tc, u16 count, u16 offset)
  2444. {
  2445. if (tc >= dev->num_tc)
  2446. return -EINVAL;
  2447. #ifdef CONFIG_XPS
  2448. netif_reset_xps_queues(dev, offset, count);
  2449. #endif
  2450. dev->tc_to_txq[tc].count = count;
  2451. dev->tc_to_txq[tc].offset = offset;
  2452. return 0;
  2453. }
  2454. EXPORT_SYMBOL(netdev_set_tc_queue);
  2455. int netdev_set_num_tc(struct net_device *dev, u8 num_tc)
  2456. {
  2457. if (num_tc > TC_MAX_QUEUE)
  2458. return -EINVAL;
  2459. #ifdef CONFIG_XPS
  2460. netif_reset_xps_queues_gt(dev, 0);
  2461. #endif
  2462. netdev_unbind_all_sb_channels(dev);
  2463. dev->num_tc = num_tc;
  2464. return 0;
  2465. }
  2466. EXPORT_SYMBOL(netdev_set_num_tc);
  2467. void netdev_unbind_sb_channel(struct net_device *dev,
  2468. struct net_device *sb_dev)
  2469. {
  2470. struct netdev_queue *txq = &dev->_tx[dev->num_tx_queues];
  2471. #ifdef CONFIG_XPS
  2472. netif_reset_xps_queues_gt(sb_dev, 0);
  2473. #endif
  2474. memset(sb_dev->tc_to_txq, 0, sizeof(sb_dev->tc_to_txq));
  2475. memset(sb_dev->prio_tc_map, 0, sizeof(sb_dev->prio_tc_map));
  2476. while (txq-- != &dev->_tx[0]) {
  2477. if (txq->sb_dev == sb_dev)
  2478. txq->sb_dev = NULL;
  2479. }
  2480. }
  2481. EXPORT_SYMBOL(netdev_unbind_sb_channel);
  2482. int netdev_bind_sb_channel_queue(struct net_device *dev,
  2483. struct net_device *sb_dev,
  2484. u8 tc, u16 count, u16 offset)
  2485. {
  2486. /* Make certain the sb_dev and dev are already configured */
  2487. if (sb_dev->num_tc >= 0 || tc >= dev->num_tc)
  2488. return -EINVAL;
  2489. /* We cannot hand out queues we don't have */
  2490. if ((offset + count) > dev->real_num_tx_queues)
  2491. return -EINVAL;
  2492. /* Record the mapping */
  2493. sb_dev->tc_to_txq[tc].count = count;
  2494. sb_dev->tc_to_txq[tc].offset = offset;
  2495. /* Provide a way for Tx queue to find the tc_to_txq map or
  2496. * XPS map for itself.
  2497. */
  2498. while (count--)
  2499. netdev_get_tx_queue(dev, count + offset)->sb_dev = sb_dev;
  2500. return 0;
  2501. }
  2502. EXPORT_SYMBOL(netdev_bind_sb_channel_queue);
  2503. int netdev_set_sb_channel(struct net_device *dev, u16 channel)
  2504. {
  2505. /* Do not use a multiqueue device to represent a subordinate channel */
  2506. if (netif_is_multiqueue(dev))
  2507. return -ENODEV;
  2508. /* We allow channels 1 - 32767 to be used for subordinate channels.
  2509. * Channel 0 is meant to be "native" mode and used only to represent
  2510. * the main root device. We allow writing 0 to reset the device back
  2511. * to normal mode after being used as a subordinate channel.
  2512. */
  2513. if (channel > S16_MAX)
  2514. return -EINVAL;
  2515. dev->num_tc = -channel;
  2516. return 0;
  2517. }
  2518. EXPORT_SYMBOL(netdev_set_sb_channel);
  2519. /*
  2520. * Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
  2521. * greater than real_num_tx_queues stale skbs on the qdisc must be flushed.
  2522. */
  2523. int netif_set_real_num_tx_queues(struct net_device *dev, unsigned int txq)
  2524. {
  2525. bool disabling;
  2526. int rc;
  2527. disabling = txq < dev->real_num_tx_queues;
  2528. if (txq < 1 || txq > dev->num_tx_queues)
  2529. return -EINVAL;
  2530. if (dev->reg_state == NETREG_REGISTERED ||
  2531. dev->reg_state == NETREG_UNREGISTERING) {
  2532. ASSERT_RTNL();
  2533. rc = netdev_queue_update_kobjects(dev, dev->real_num_tx_queues,
  2534. txq);
  2535. if (rc)
  2536. return rc;
  2537. if (dev->num_tc)
  2538. netif_setup_tc(dev, txq);
  2539. dev_qdisc_change_real_num_tx(dev, txq);
  2540. dev->real_num_tx_queues = txq;
  2541. if (disabling) {
  2542. synchronize_net();
  2543. qdisc_reset_all_tx_gt(dev, txq);
  2544. #ifdef CONFIG_XPS
  2545. netif_reset_xps_queues_gt(dev, txq);
  2546. #endif
  2547. }
  2548. } else {
  2549. dev->real_num_tx_queues = txq;
  2550. }
  2551. return 0;
  2552. }
  2553. EXPORT_SYMBOL(netif_set_real_num_tx_queues);
  2554. #ifdef CONFIG_SYSFS
  2555. /**
  2556. * netif_set_real_num_rx_queues - set actual number of RX queues used
  2557. * @dev: Network device
  2558. * @rxq: Actual number of RX queues
  2559. *
  2560. * This must be called either with the rtnl_lock held or before
  2561. * registration of the net device. Returns 0 on success, or a
  2562. * negative error code. If called before registration, it always
  2563. * succeeds.
  2564. */
  2565. int netif_set_real_num_rx_queues(struct net_device *dev, unsigned int rxq)
  2566. {
  2567. int rc;
  2568. if (rxq < 1 || rxq > dev->num_rx_queues)
  2569. return -EINVAL;
  2570. if (dev->reg_state == NETREG_REGISTERED) {
  2571. ASSERT_RTNL();
  2572. rc = net_rx_queue_update_kobjects(dev, dev->real_num_rx_queues,
  2573. rxq);
  2574. if (rc)
  2575. return rc;
  2576. }
  2577. dev->real_num_rx_queues = rxq;
  2578. return 0;
  2579. }
  2580. EXPORT_SYMBOL(netif_set_real_num_rx_queues);
  2581. #endif
  2582. /**
  2583. * netif_set_real_num_queues - set actual number of RX and TX queues used
  2584. * @dev: Network device
  2585. * @txq: Actual number of TX queues
  2586. * @rxq: Actual number of RX queues
  2587. *
  2588. * Set the real number of both TX and RX queues.
  2589. * Does nothing if the number of queues is already correct.
  2590. */
  2591. int netif_set_real_num_queues(struct net_device *dev,
  2592. unsigned int txq, unsigned int rxq)
  2593. {
  2594. unsigned int old_rxq = dev->real_num_rx_queues;
  2595. int err;
  2596. if (txq < 1 || txq > dev->num_tx_queues ||
  2597. rxq < 1 || rxq > dev->num_rx_queues)
  2598. return -EINVAL;
  2599. /* Start from increases, so the error path only does decreases -
  2600. * decreases can't fail.
  2601. */
  2602. if (rxq > dev->real_num_rx_queues) {
  2603. err = netif_set_real_num_rx_queues(dev, rxq);
  2604. if (err)
  2605. return err;
  2606. }
  2607. if (txq > dev->real_num_tx_queues) {
  2608. err = netif_set_real_num_tx_queues(dev, txq);
  2609. if (err)
  2610. goto undo_rx;
  2611. }
  2612. if (rxq < dev->real_num_rx_queues)
  2613. WARN_ON(netif_set_real_num_rx_queues(dev, rxq));
  2614. if (txq < dev->real_num_tx_queues)
  2615. WARN_ON(netif_set_real_num_tx_queues(dev, txq));
  2616. return 0;
  2617. undo_rx:
  2618. WARN_ON(netif_set_real_num_rx_queues(dev, old_rxq));
  2619. return err;
  2620. }
  2621. EXPORT_SYMBOL(netif_set_real_num_queues);
  2622. /**
  2623. * netif_set_tso_max_size() - set the max size of TSO frames supported
  2624. * @dev: netdev to update
  2625. * @size: max skb->len of a TSO frame
  2626. *
  2627. * Set the limit on the size of TSO super-frames the device can handle.
  2628. * Unless explicitly set the stack will assume the value of
  2629. * %GSO_LEGACY_MAX_SIZE.
  2630. */
  2631. void netif_set_tso_max_size(struct net_device *dev, unsigned int size)
  2632. {
  2633. dev->tso_max_size = min(GSO_MAX_SIZE, size);
  2634. if (size < READ_ONCE(dev->gso_max_size))
  2635. netif_set_gso_max_size(dev, size);
  2636. if (size < READ_ONCE(dev->gso_ipv4_max_size))
  2637. netif_set_gso_ipv4_max_size(dev, size);
  2638. }
  2639. EXPORT_SYMBOL(netif_set_tso_max_size);
  2640. /**
  2641. * netif_set_tso_max_segs() - set the max number of segs supported for TSO
  2642. * @dev: netdev to update
  2643. * @segs: max number of TCP segments
  2644. *
  2645. * Set the limit on the number of TCP segments the device can generate from
  2646. * a single TSO super-frame.
  2647. * Unless explicitly set the stack will assume the value of %GSO_MAX_SEGS.
  2648. */
  2649. void netif_set_tso_max_segs(struct net_device *dev, unsigned int segs)
  2650. {
  2651. dev->tso_max_segs = segs;
  2652. if (segs < READ_ONCE(dev->gso_max_segs))
  2653. netif_set_gso_max_segs(dev, segs);
  2654. }
  2655. EXPORT_SYMBOL(netif_set_tso_max_segs);
  2656. /**
  2657. * netif_inherit_tso_max() - copy all TSO limits from a lower device to an upper
  2658. * @to: netdev to update
  2659. * @from: netdev from which to copy the limits
  2660. */
  2661. void netif_inherit_tso_max(struct net_device *to, const struct net_device *from)
  2662. {
  2663. netif_set_tso_max_size(to, from->tso_max_size);
  2664. netif_set_tso_max_segs(to, from->tso_max_segs);
  2665. }
  2666. EXPORT_SYMBOL(netif_inherit_tso_max);
  2667. /**
  2668. * netif_get_num_default_rss_queues - default number of RSS queues
  2669. *
  2670. * Default value is the number of physical cores if there are only 1 or 2, or
  2671. * divided by 2 if there are more.
  2672. */
  2673. int netif_get_num_default_rss_queues(void)
  2674. {
  2675. cpumask_var_t cpus;
  2676. int cpu, count = 0;
  2677. if (unlikely(is_kdump_kernel() || !zalloc_cpumask_var(&cpus, GFP_KERNEL)))
  2678. return 1;
  2679. cpumask_copy(cpus, cpu_online_mask);
  2680. for_each_cpu(cpu, cpus) {
  2681. ++count;
  2682. cpumask_andnot(cpus, cpus, topology_sibling_cpumask(cpu));
  2683. }
  2684. free_cpumask_var(cpus);
  2685. return count > 2 ? DIV_ROUND_UP(count, 2) : count;
  2686. }
  2687. EXPORT_SYMBOL(netif_get_num_default_rss_queues);
  2688. static void __netif_reschedule(struct Qdisc *q)
  2689. {
  2690. struct softnet_data *sd;
  2691. unsigned long flags;
  2692. local_irq_save(flags);
  2693. sd = this_cpu_ptr(&softnet_data);
  2694. q->next_sched = NULL;
  2695. *sd->output_queue_tailp = q;
  2696. sd->output_queue_tailp = &q->next_sched;
  2697. raise_softirq_irqoff(NET_TX_SOFTIRQ);
  2698. local_irq_restore(flags);
  2699. }
  2700. void __netif_schedule(struct Qdisc *q)
  2701. {
  2702. if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
  2703. __netif_reschedule(q);
  2704. }
  2705. EXPORT_SYMBOL(__netif_schedule);
  2706. struct dev_kfree_skb_cb {
  2707. enum skb_drop_reason reason;
  2708. };
  2709. static struct dev_kfree_skb_cb *get_kfree_skb_cb(const struct sk_buff *skb)
  2710. {
  2711. return (struct dev_kfree_skb_cb *)skb->cb;
  2712. }
  2713. void netif_schedule_queue(struct netdev_queue *txq)
  2714. {
  2715. rcu_read_lock();
  2716. if (!netif_xmit_stopped(txq)) {
  2717. struct Qdisc *q = rcu_dereference(txq->qdisc);
  2718. __netif_schedule(q);
  2719. }
  2720. rcu_read_unlock();
  2721. }
  2722. EXPORT_SYMBOL(netif_schedule_queue);
  2723. void netif_tx_wake_queue(struct netdev_queue *dev_queue)
  2724. {
  2725. if (test_and_clear_bit(__QUEUE_STATE_DRV_XOFF, &dev_queue->state)) {
  2726. struct Qdisc *q;
  2727. rcu_read_lock();
  2728. q = rcu_dereference(dev_queue->qdisc);
  2729. __netif_schedule(q);
  2730. rcu_read_unlock();
  2731. }
  2732. }
  2733. EXPORT_SYMBOL(netif_tx_wake_queue);
  2734. void dev_kfree_skb_irq_reason(struct sk_buff *skb, enum skb_drop_reason reason)
  2735. {
  2736. unsigned long flags;
  2737. if (unlikely(!skb))
  2738. return;
  2739. if (likely(refcount_read(&skb->users) == 1)) {
  2740. smp_rmb();
  2741. refcount_set(&skb->users, 0);
  2742. } else if (likely(!refcount_dec_and_test(&skb->users))) {
  2743. return;
  2744. }
  2745. get_kfree_skb_cb(skb)->reason = reason;
  2746. local_irq_save(flags);
  2747. skb->next = __this_cpu_read(softnet_data.completion_queue);
  2748. __this_cpu_write(softnet_data.completion_queue, skb);
  2749. raise_softirq_irqoff(NET_TX_SOFTIRQ);
  2750. local_irq_restore(flags);
  2751. }
  2752. EXPORT_SYMBOL(dev_kfree_skb_irq_reason);
  2753. void dev_kfree_skb_any_reason(struct sk_buff *skb, enum skb_drop_reason reason)
  2754. {
  2755. if (in_hardirq() || irqs_disabled())
  2756. dev_kfree_skb_irq_reason(skb, reason);
  2757. else
  2758. kfree_skb_reason(skb, reason);
  2759. }
  2760. EXPORT_SYMBOL(dev_kfree_skb_any_reason);
  2761. /**
  2762. * netif_device_detach - mark device as removed
  2763. * @dev: network device
  2764. *
  2765. * Mark device as removed from system and therefore no longer available.
  2766. */
  2767. void netif_device_detach(struct net_device *dev)
  2768. {
  2769. if (test_and_clear_bit(__LINK_STATE_PRESENT, &dev->state) &&
  2770. netif_running(dev)) {
  2771. netif_tx_stop_all_queues(dev);
  2772. }
  2773. }
  2774. EXPORT_SYMBOL(netif_device_detach);
  2775. /**
  2776. * netif_device_attach - mark device as attached
  2777. * @dev: network device
  2778. *
  2779. * Mark device as attached from system and restart if needed.
  2780. */
  2781. void netif_device_attach(struct net_device *dev)
  2782. {
  2783. if (!test_and_set_bit(__LINK_STATE_PRESENT, &dev->state) &&
  2784. netif_running(dev)) {
  2785. netif_tx_wake_all_queues(dev);
  2786. __netdev_watchdog_up(dev);
  2787. }
  2788. }
  2789. EXPORT_SYMBOL(netif_device_attach);
  2790. /*
  2791. * Returns a Tx hash based on the given packet descriptor a Tx queues' number
  2792. * to be used as a distribution range.
  2793. */
  2794. static u16 skb_tx_hash(const struct net_device *dev,
  2795. const struct net_device *sb_dev,
  2796. struct sk_buff *skb)
  2797. {
  2798. u32 hash;
  2799. u16 qoffset = 0;
  2800. u16 qcount = dev->real_num_tx_queues;
  2801. if (dev->num_tc) {
  2802. u8 tc = netdev_get_prio_tc_map(dev, skb->priority);
  2803. qoffset = sb_dev->tc_to_txq[tc].offset;
  2804. qcount = sb_dev->tc_to_txq[tc].count;
  2805. if (unlikely(!qcount)) {
  2806. net_warn_ratelimited("%s: invalid qcount, qoffset %u for tc %u\n",
  2807. sb_dev->name, qoffset, tc);
  2808. qoffset = 0;
  2809. qcount = dev->real_num_tx_queues;
  2810. }
  2811. }
  2812. if (skb_rx_queue_recorded(skb)) {
  2813. DEBUG_NET_WARN_ON_ONCE(qcount == 0);
  2814. hash = skb_get_rx_queue(skb);
  2815. if (hash >= qoffset)
  2816. hash -= qoffset;
  2817. while (unlikely(hash >= qcount))
  2818. hash -= qcount;
  2819. return hash + qoffset;
  2820. }
  2821. return (u16) reciprocal_scale(skb_get_hash(skb), qcount) + qoffset;
  2822. }
  2823. void skb_warn_bad_offload(const struct sk_buff *skb)
  2824. {
  2825. static const netdev_features_t null_features;
  2826. struct net_device *dev = skb->dev;
  2827. const char *name = "";
  2828. if (!net_ratelimit())
  2829. return;
  2830. if (dev) {
  2831. if (dev->dev.parent)
  2832. name = dev_driver_string(dev->dev.parent);
  2833. else
  2834. name = netdev_name(dev);
  2835. }
  2836. skb_dump(KERN_WARNING, skb, false);
  2837. WARN(1, "%s: caps=(%pNF, %pNF)\n",
  2838. name, dev ? &dev->features : &null_features,
  2839. skb->sk ? &skb->sk->sk_route_caps : &null_features);
  2840. }
  2841. /*
  2842. * Invalidate hardware checksum when packet is to be mangled, and
  2843. * complete checksum manually on outgoing path.
  2844. */
  2845. int skb_checksum_help(struct sk_buff *skb)
  2846. {
  2847. __wsum csum;
  2848. int ret = 0, offset;
  2849. if (skb->ip_summed == CHECKSUM_COMPLETE)
  2850. goto out_set_summed;
  2851. if (unlikely(skb_is_gso(skb))) {
  2852. skb_warn_bad_offload(skb);
  2853. return -EINVAL;
  2854. }
  2855. if (!skb_frags_readable(skb)) {
  2856. return -EFAULT;
  2857. }
  2858. /* Before computing a checksum, we should make sure no frag could
  2859. * be modified by an external entity : checksum could be wrong.
  2860. */
  2861. if (skb_has_shared_frag(skb)) {
  2862. ret = __skb_linearize(skb);
  2863. if (ret)
  2864. goto out;
  2865. }
  2866. offset = skb_checksum_start_offset(skb);
  2867. ret = -EINVAL;
  2868. if (unlikely(offset >= skb_headlen(skb))) {
  2869. DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
  2870. WARN_ONCE(true, "offset (%d) >= skb_headlen() (%u)\n",
  2871. offset, skb_headlen(skb));
  2872. goto out;
  2873. }
  2874. csum = skb_checksum(skb, offset, skb->len - offset, 0);
  2875. offset += skb->csum_offset;
  2876. if (unlikely(offset + sizeof(__sum16) > skb_headlen(skb))) {
  2877. DO_ONCE_LITE(skb_dump, KERN_ERR, skb, false);
  2878. WARN_ONCE(true, "offset+2 (%zu) > skb_headlen() (%u)\n",
  2879. offset + sizeof(__sum16), skb_headlen(skb));
  2880. goto out;
  2881. }
  2882. ret = skb_ensure_writable(skb, offset + sizeof(__sum16));
  2883. if (ret)
  2884. goto out;
  2885. *(__sum16 *)(skb->data + offset) = csum_fold(csum) ?: CSUM_MANGLED_0;
  2886. out_set_summed:
  2887. skb->ip_summed = CHECKSUM_NONE;
  2888. out:
  2889. return ret;
  2890. }
  2891. EXPORT_SYMBOL(skb_checksum_help);
  2892. int skb_crc32c_csum_help(struct sk_buff *skb)
  2893. {
  2894. __le32 crc32c_csum;
  2895. int ret = 0, offset, start;
  2896. if (skb->ip_summed != CHECKSUM_PARTIAL)
  2897. goto out;
  2898. if (unlikely(skb_is_gso(skb)))
  2899. goto out;
  2900. /* Before computing a checksum, we should make sure no frag could
  2901. * be modified by an external entity : checksum could be wrong.
  2902. */
  2903. if (unlikely(skb_has_shared_frag(skb))) {
  2904. ret = __skb_linearize(skb);
  2905. if (ret)
  2906. goto out;
  2907. }
  2908. start = skb_checksum_start_offset(skb);
  2909. offset = start + offsetof(struct sctphdr, checksum);
  2910. if (WARN_ON_ONCE(offset >= skb_headlen(skb))) {
  2911. ret = -EINVAL;
  2912. goto out;
  2913. }
  2914. ret = skb_ensure_writable(skb, offset + sizeof(__le32));
  2915. if (ret)
  2916. goto out;
  2917. crc32c_csum = cpu_to_le32(~__skb_checksum(skb, start,
  2918. skb->len - start, ~(__u32)0,
  2919. crc32c_csum_stub));
  2920. *(__le32 *)(skb->data + offset) = crc32c_csum;
  2921. skb_reset_csum_not_inet(skb);
  2922. out:
  2923. return ret;
  2924. }
  2925. EXPORT_SYMBOL(skb_crc32c_csum_help);
  2926. __be16 skb_network_protocol(struct sk_buff *skb, int *depth)
  2927. {
  2928. __be16 type = skb->protocol;
  2929. /* Tunnel gso handlers can set protocol to ethernet. */
  2930. if (type == htons(ETH_P_TEB)) {
  2931. struct ethhdr *eth;
  2932. if (unlikely(!pskb_may_pull(skb, sizeof(struct ethhdr))))
  2933. return 0;
  2934. eth = (struct ethhdr *)skb->data;
  2935. type = eth->h_proto;
  2936. }
  2937. return vlan_get_protocol_and_depth(skb, type, depth);
  2938. }
  2939. /* Take action when hardware reception checksum errors are detected. */
  2940. #ifdef CONFIG_BUG
  2941. static void do_netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
  2942. {
  2943. netdev_err(dev, "hw csum failure\n");
  2944. skb_dump(KERN_ERR, skb, true);
  2945. dump_stack();
  2946. }
  2947. void netdev_rx_csum_fault(struct net_device *dev, struct sk_buff *skb)
  2948. {
  2949. DO_ONCE_LITE(do_netdev_rx_csum_fault, dev, skb);
  2950. }
  2951. EXPORT_SYMBOL(netdev_rx_csum_fault);
  2952. #endif
  2953. /* XXX: check that highmem exists at all on the given machine. */
  2954. static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
  2955. {
  2956. #ifdef CONFIG_HIGHMEM
  2957. int i;
  2958. if (!(dev->features & NETIF_F_HIGHDMA)) {
  2959. for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
  2960. skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
  2961. struct page *page = skb_frag_page(frag);
  2962. if (page && PageHighMem(page))
  2963. return 1;
  2964. }
  2965. }
  2966. #endif
  2967. return 0;
  2968. }
  2969. /* If MPLS offload request, verify we are testing hardware MPLS features
  2970. * instead of standard features for the netdev.
  2971. */
  2972. #if IS_ENABLED(CONFIG_NET_MPLS_GSO)
  2973. static netdev_features_t net_mpls_features(struct sk_buff *skb,
  2974. netdev_features_t features,
  2975. __be16 type)
  2976. {
  2977. if (eth_p_mpls(type))
  2978. features &= skb->dev->mpls_features;
  2979. return features;
  2980. }
  2981. #else
  2982. static netdev_features_t net_mpls_features(struct sk_buff *skb,
  2983. netdev_features_t features,
  2984. __be16 type)
  2985. {
  2986. return features;
  2987. }
  2988. #endif
  2989. static netdev_features_t harmonize_features(struct sk_buff *skb,
  2990. netdev_features_t features)
  2991. {
  2992. __be16 type;
  2993. type = skb_network_protocol(skb, NULL);
  2994. features = net_mpls_features(skb, features, type);
  2995. if (skb->ip_summed != CHECKSUM_NONE &&
  2996. !can_checksum_protocol(features, type)) {
  2997. features &= ~(NETIF_F_CSUM_MASK | NETIF_F_GSO_MASK);
  2998. }
  2999. if (illegal_highdma(skb->dev, skb))
  3000. features &= ~NETIF_F_SG;
  3001. return features;
  3002. }
  3003. netdev_features_t passthru_features_check(struct sk_buff *skb,
  3004. struct net_device *dev,
  3005. netdev_features_t features)
  3006. {
  3007. return features;
  3008. }
  3009. EXPORT_SYMBOL(passthru_features_check);
  3010. static netdev_features_t dflt_features_check(struct sk_buff *skb,
  3011. struct net_device *dev,
  3012. netdev_features_t features)
  3013. {
  3014. return vlan_features_check(skb, features);
  3015. }
  3016. static netdev_features_t gso_features_check(const struct sk_buff *skb,
  3017. struct net_device *dev,
  3018. netdev_features_t features)
  3019. {
  3020. u16 gso_segs = skb_shinfo(skb)->gso_segs;
  3021. if (gso_segs > READ_ONCE(dev->gso_max_segs))
  3022. return features & ~NETIF_F_GSO_MASK;
  3023. if (unlikely(skb->len >= netif_get_gso_max_size(dev, skb)))
  3024. return features & ~NETIF_F_GSO_MASK;
  3025. if (!skb_shinfo(skb)->gso_type) {
  3026. skb_warn_bad_offload(skb);
  3027. return features & ~NETIF_F_GSO_MASK;
  3028. }
  3029. /* Support for GSO partial features requires software
  3030. * intervention before we can actually process the packets
  3031. * so we need to strip support for any partial features now
  3032. * and we can pull them back in after we have partially
  3033. * segmented the frame.
  3034. */
  3035. if (!(skb_shinfo(skb)->gso_type & SKB_GSO_PARTIAL))
  3036. features &= ~dev->gso_partial_features;
  3037. /* Make sure to clear the IPv4 ID mangling feature if the
  3038. * IPv4 header has the potential to be fragmented.
  3039. */
  3040. if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) {
  3041. struct iphdr *iph = skb->encapsulation ?
  3042. inner_ip_hdr(skb) : ip_hdr(skb);
  3043. if (!(iph->frag_off & htons(IP_DF)))
  3044. features &= ~NETIF_F_TSO_MANGLEID;
  3045. }
  3046. /* NETIF_F_IPV6_CSUM does not support IPv6 extension headers,
  3047. * so neither does TSO that depends on it.
  3048. */
  3049. if (features & NETIF_F_IPV6_CSUM &&
  3050. (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6 ||
  3051. (skb_shinfo(skb)->gso_type & SKB_GSO_UDP_L4 &&
  3052. vlan_get_protocol(skb) == htons(ETH_P_IPV6))) &&
  3053. skb_transport_header_was_set(skb) &&
  3054. skb_network_header_len(skb) != sizeof(struct ipv6hdr) &&
  3055. !ipv6_has_hopopt_jumbo(skb))
  3056. features &= ~(NETIF_F_IPV6_CSUM | NETIF_F_TSO6 | NETIF_F_GSO_UDP_L4);
  3057. return features;
  3058. }
  3059. netdev_features_t netif_skb_features(struct sk_buff *skb)
  3060. {
  3061. struct net_device *dev = skb->dev;
  3062. netdev_features_t features = dev->features;
  3063. if (skb_is_gso(skb))
  3064. features = gso_features_check(skb, dev, features);
  3065. /* If encapsulation offload request, verify we are testing
  3066. * hardware encapsulation features instead of standard
  3067. * features for the netdev
  3068. */
  3069. if (skb->encapsulation)
  3070. features &= dev->hw_enc_features;
  3071. if (skb_vlan_tagged(skb))
  3072. features = netdev_intersect_features(features,
  3073. dev->vlan_features |
  3074. NETIF_F_HW_VLAN_CTAG_TX |
  3075. NETIF_F_HW_VLAN_STAG_TX);
  3076. if (dev->netdev_ops->ndo_features_check)
  3077. features &= dev->netdev_ops->ndo_features_check(skb, dev,
  3078. features);
  3079. else
  3080. features &= dflt_features_check(skb, dev, features);
  3081. return harmonize_features(skb, features);
  3082. }
  3083. EXPORT_SYMBOL(netif_skb_features);
  3084. static int xmit_one(struct sk_buff *skb, struct net_device *dev,
  3085. struct netdev_queue *txq, bool more)
  3086. {
  3087. unsigned int len;
  3088. int rc;
  3089. if (dev_nit_active(dev))
  3090. dev_queue_xmit_nit(skb, dev);
  3091. len = skb->len;
  3092. trace_net_dev_start_xmit(skb, dev);
  3093. rc = netdev_start_xmit(skb, dev, txq, more);
  3094. trace_net_dev_xmit(skb, rc, dev, len);
  3095. return rc;
  3096. }
  3097. struct sk_buff *dev_hard_start_xmit(struct sk_buff *first, struct net_device *dev,
  3098. struct netdev_queue *txq, int *ret)
  3099. {
  3100. struct sk_buff *skb = first;
  3101. int rc = NETDEV_TX_OK;
  3102. while (skb) {
  3103. struct sk_buff *next = skb->next;
  3104. skb_mark_not_on_list(skb);
  3105. rc = xmit_one(skb, dev, txq, next != NULL);
  3106. if (unlikely(!dev_xmit_complete(rc))) {
  3107. skb->next = next;
  3108. goto out;
  3109. }
  3110. skb = next;
  3111. if (netif_tx_queue_stopped(txq) && skb) {
  3112. rc = NETDEV_TX_BUSY;
  3113. break;
  3114. }
  3115. }
  3116. out:
  3117. *ret = rc;
  3118. return skb;
  3119. }
  3120. static struct sk_buff *validate_xmit_vlan(struct sk_buff *skb,
  3121. netdev_features_t features)
  3122. {
  3123. if (skb_vlan_tag_present(skb) &&
  3124. !vlan_hw_offload_capable(features, skb->vlan_proto))
  3125. skb = __vlan_hwaccel_push_inside(skb);
  3126. return skb;
  3127. }
  3128. int skb_csum_hwoffload_help(struct sk_buff *skb,
  3129. const netdev_features_t features)
  3130. {
  3131. if (unlikely(skb_csum_is_sctp(skb)))
  3132. return !!(features & NETIF_F_SCTP_CRC) ? 0 :
  3133. skb_crc32c_csum_help(skb);
  3134. if (features & NETIF_F_HW_CSUM)
  3135. return 0;
  3136. if (features & (NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM)) {
  3137. if (vlan_get_protocol(skb) == htons(ETH_P_IPV6) &&
  3138. skb_network_header_len(skb) != sizeof(struct ipv6hdr) &&
  3139. !ipv6_has_hopopt_jumbo(skb))
  3140. goto sw_checksum;
  3141. switch (skb->csum_offset) {
  3142. case offsetof(struct tcphdr, check):
  3143. case offsetof(struct udphdr, check):
  3144. return 0;
  3145. }
  3146. }
  3147. sw_checksum:
  3148. return skb_checksum_help(skb);
  3149. }
  3150. EXPORT_SYMBOL(skb_csum_hwoffload_help);
  3151. static struct sk_buff *validate_xmit_skb(struct sk_buff *skb, struct net_device *dev, bool *again)
  3152. {
  3153. netdev_features_t features;
  3154. if (!skb_frags_readable(skb))
  3155. goto out_kfree_skb;
  3156. features = netif_skb_features(skb);
  3157. skb = validate_xmit_vlan(skb, features);
  3158. if (unlikely(!skb))
  3159. goto out_null;
  3160. skb = sk_validate_xmit_skb(skb, dev);
  3161. if (unlikely(!skb))
  3162. goto out_null;
  3163. if (netif_needs_gso(skb, features)) {
  3164. struct sk_buff *segs;
  3165. segs = skb_gso_segment(skb, features);
  3166. if (IS_ERR(segs)) {
  3167. goto out_kfree_skb;
  3168. } else if (segs) {
  3169. consume_skb(skb);
  3170. skb = segs;
  3171. }
  3172. } else {
  3173. if (skb_needs_linearize(skb, features) &&
  3174. __skb_linearize(skb))
  3175. goto out_kfree_skb;
  3176. /* If packet is not checksummed and device does not
  3177. * support checksumming for this protocol, complete
  3178. * checksumming here.
  3179. */
  3180. if (skb->ip_summed == CHECKSUM_PARTIAL) {
  3181. if (skb->encapsulation)
  3182. skb_set_inner_transport_header(skb,
  3183. skb_checksum_start_offset(skb));
  3184. else
  3185. skb_set_transport_header(skb,
  3186. skb_checksum_start_offset(skb));
  3187. if (skb_csum_hwoffload_help(skb, features))
  3188. goto out_kfree_skb;
  3189. }
  3190. }
  3191. skb = validate_xmit_xfrm(skb, features, again);
  3192. return skb;
  3193. out_kfree_skb:
  3194. kfree_skb(skb);
  3195. out_null:
  3196. dev_core_stats_tx_dropped_inc(dev);
  3197. return NULL;
  3198. }
  3199. struct sk_buff *validate_xmit_skb_list(struct sk_buff *skb, struct net_device *dev, bool *again)
  3200. {
  3201. struct sk_buff *next, *head = NULL, *tail;
  3202. for (; skb != NULL; skb = next) {
  3203. next = skb->next;
  3204. skb_mark_not_on_list(skb);
  3205. /* in case skb won't be segmented, point to itself */
  3206. skb->prev = skb;
  3207. skb = validate_xmit_skb(skb, dev, again);
  3208. if (!skb)
  3209. continue;
  3210. if (!head)
  3211. head = skb;
  3212. else
  3213. tail->next = skb;
  3214. /* If skb was segmented, skb->prev points to
  3215. * the last segment. If not, it still contains skb.
  3216. */
  3217. tail = skb->prev;
  3218. }
  3219. return head;
  3220. }
  3221. EXPORT_SYMBOL_GPL(validate_xmit_skb_list);
  3222. static void qdisc_pkt_len_init(struct sk_buff *skb)
  3223. {
  3224. const struct skb_shared_info *shinfo = skb_shinfo(skb);
  3225. qdisc_skb_cb(skb)->pkt_len = skb->len;
  3226. /* To get more precise estimation of bytes sent on wire,
  3227. * we add to pkt_len the headers size of all segments
  3228. */
  3229. if (shinfo->gso_size && skb_transport_header_was_set(skb)) {
  3230. u16 gso_segs = shinfo->gso_segs;
  3231. unsigned int hdr_len;
  3232. /* mac layer + network layer */
  3233. hdr_len = skb_transport_offset(skb);
  3234. /* + transport layer */
  3235. if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
  3236. const struct tcphdr *th;
  3237. struct tcphdr _tcphdr;
  3238. th = skb_header_pointer(skb, hdr_len,
  3239. sizeof(_tcphdr), &_tcphdr);
  3240. if (likely(th))
  3241. hdr_len += __tcp_hdrlen(th);
  3242. } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
  3243. struct udphdr _udphdr;
  3244. if (skb_header_pointer(skb, hdr_len,
  3245. sizeof(_udphdr), &_udphdr))
  3246. hdr_len += sizeof(struct udphdr);
  3247. }
  3248. if (unlikely(shinfo->gso_type & SKB_GSO_DODGY)) {
  3249. int payload = skb->len - hdr_len;
  3250. /* Malicious packet. */
  3251. if (payload <= 0)
  3252. return;
  3253. gso_segs = DIV_ROUND_UP(payload, shinfo->gso_size);
  3254. }
  3255. qdisc_skb_cb(skb)->pkt_len += (gso_segs - 1) * hdr_len;
  3256. }
  3257. }
  3258. static int dev_qdisc_enqueue(struct sk_buff *skb, struct Qdisc *q,
  3259. struct sk_buff **to_free,
  3260. struct netdev_queue *txq)
  3261. {
  3262. int rc;
  3263. rc = q->enqueue(skb, q, to_free) & NET_XMIT_MASK;
  3264. if (rc == NET_XMIT_SUCCESS)
  3265. trace_qdisc_enqueue(q, txq, skb);
  3266. return rc;
  3267. }
  3268. static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
  3269. struct net_device *dev,
  3270. struct netdev_queue *txq)
  3271. {
  3272. spinlock_t *root_lock = qdisc_lock(q);
  3273. struct sk_buff *to_free = NULL;
  3274. bool contended;
  3275. int rc;
  3276. qdisc_calculate_pkt_len(skb, q);
  3277. tcf_set_drop_reason(skb, SKB_DROP_REASON_QDISC_DROP);
  3278. if (q->flags & TCQ_F_NOLOCK) {
  3279. if (q->flags & TCQ_F_CAN_BYPASS && nolock_qdisc_is_empty(q) &&
  3280. qdisc_run_begin(q)) {
  3281. /* Retest nolock_qdisc_is_empty() within the protection
  3282. * of q->seqlock to protect from racing with requeuing.
  3283. */
  3284. if (unlikely(!nolock_qdisc_is_empty(q))) {
  3285. rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
  3286. __qdisc_run(q);
  3287. qdisc_run_end(q);
  3288. goto no_lock_out;
  3289. }
  3290. qdisc_bstats_cpu_update(q, skb);
  3291. if (sch_direct_xmit(skb, q, dev, txq, NULL, true) &&
  3292. !nolock_qdisc_is_empty(q))
  3293. __qdisc_run(q);
  3294. qdisc_run_end(q);
  3295. return NET_XMIT_SUCCESS;
  3296. }
  3297. rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
  3298. qdisc_run(q);
  3299. no_lock_out:
  3300. if (unlikely(to_free))
  3301. kfree_skb_list_reason(to_free,
  3302. tcf_get_drop_reason(to_free));
  3303. return rc;
  3304. }
  3305. if (unlikely(READ_ONCE(q->owner) == smp_processor_id())) {
  3306. kfree_skb_reason(skb, SKB_DROP_REASON_TC_RECLASSIFY_LOOP);
  3307. return NET_XMIT_DROP;
  3308. }
  3309. /*
  3310. * Heuristic to force contended enqueues to serialize on a
  3311. * separate lock before trying to get qdisc main lock.
  3312. * This permits qdisc->running owner to get the lock more
  3313. * often and dequeue packets faster.
  3314. * On PREEMPT_RT it is possible to preempt the qdisc owner during xmit
  3315. * and then other tasks will only enqueue packets. The packets will be
  3316. * sent after the qdisc owner is scheduled again. To prevent this
  3317. * scenario the task always serialize on the lock.
  3318. */
  3319. contended = qdisc_is_running(q) || IS_ENABLED(CONFIG_PREEMPT_RT);
  3320. if (unlikely(contended))
  3321. spin_lock(&q->busylock);
  3322. spin_lock(root_lock);
  3323. if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED, &q->state))) {
  3324. __qdisc_drop(skb, &to_free);
  3325. rc = NET_XMIT_DROP;
  3326. } else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
  3327. qdisc_run_begin(q)) {
  3328. /*
  3329. * This is a work-conserving queue; there are no old skbs
  3330. * waiting to be sent out; and the qdisc is not running -
  3331. * xmit the skb directly.
  3332. */
  3333. qdisc_bstats_update(q, skb);
  3334. if (sch_direct_xmit(skb, q, dev, txq, root_lock, true)) {
  3335. if (unlikely(contended)) {
  3336. spin_unlock(&q->busylock);
  3337. contended = false;
  3338. }
  3339. __qdisc_run(q);
  3340. }
  3341. qdisc_run_end(q);
  3342. rc = NET_XMIT_SUCCESS;
  3343. } else {
  3344. WRITE_ONCE(q->owner, smp_processor_id());
  3345. rc = dev_qdisc_enqueue(skb, q, &to_free, txq);
  3346. WRITE_ONCE(q->owner, -1);
  3347. if (qdisc_run_begin(q)) {
  3348. if (unlikely(contended)) {
  3349. spin_unlock(&q->busylock);
  3350. contended = false;
  3351. }
  3352. __qdisc_run(q);
  3353. qdisc_run_end(q);
  3354. }
  3355. }
  3356. spin_unlock(root_lock);
  3357. if (unlikely(to_free))
  3358. kfree_skb_list_reason(to_free,
  3359. tcf_get_drop_reason(to_free));
  3360. if (unlikely(contended))
  3361. spin_unlock(&q->busylock);
  3362. return rc;
  3363. }
  3364. #if IS_ENABLED(CONFIG_CGROUP_NET_PRIO)
  3365. static void skb_update_prio(struct sk_buff *skb)
  3366. {
  3367. const struct netprio_map *map;
  3368. const struct sock *sk;
  3369. unsigned int prioidx;
  3370. if (skb->priority)
  3371. return;
  3372. map = rcu_dereference_bh(skb->dev->priomap);
  3373. if (!map)
  3374. return;
  3375. sk = skb_to_full_sk(skb);
  3376. if (!sk)
  3377. return;
  3378. prioidx = sock_cgroup_prioidx(&sk->sk_cgrp_data);
  3379. if (prioidx < map->priomap_len)
  3380. skb->priority = map->priomap[prioidx];
  3381. }
  3382. #else
  3383. #define skb_update_prio(skb)
  3384. #endif
  3385. /**
  3386. * dev_loopback_xmit - loop back @skb
  3387. * @net: network namespace this loopback is happening in
  3388. * @sk: sk needed to be a netfilter okfn
  3389. * @skb: buffer to transmit
  3390. */
  3391. int dev_loopback_xmit(struct net *net, struct sock *sk, struct sk_buff *skb)
  3392. {
  3393. skb_reset_mac_header(skb);
  3394. __skb_pull(skb, skb_network_offset(skb));
  3395. skb->pkt_type = PACKET_LOOPBACK;
  3396. if (skb->ip_summed == CHECKSUM_NONE)
  3397. skb->ip_summed = CHECKSUM_UNNECESSARY;
  3398. DEBUG_NET_WARN_ON_ONCE(!skb_dst(skb));
  3399. skb_dst_force(skb);
  3400. netif_rx(skb);
  3401. return 0;
  3402. }
  3403. EXPORT_SYMBOL(dev_loopback_xmit);
  3404. #ifdef CONFIG_NET_EGRESS
  3405. static struct netdev_queue *
  3406. netdev_tx_queue_mapping(struct net_device *dev, struct sk_buff *skb)
  3407. {
  3408. int qm = skb_get_queue_mapping(skb);
  3409. return netdev_get_tx_queue(dev, netdev_cap_txqueue(dev, qm));
  3410. }
  3411. #ifndef CONFIG_PREEMPT_RT
  3412. static bool netdev_xmit_txqueue_skipped(void)
  3413. {
  3414. return __this_cpu_read(softnet_data.xmit.skip_txqueue);
  3415. }
  3416. void netdev_xmit_skip_txqueue(bool skip)
  3417. {
  3418. __this_cpu_write(softnet_data.xmit.skip_txqueue, skip);
  3419. }
  3420. EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
  3421. #else
  3422. static bool netdev_xmit_txqueue_skipped(void)
  3423. {
  3424. return current->net_xmit.skip_txqueue;
  3425. }
  3426. void netdev_xmit_skip_txqueue(bool skip)
  3427. {
  3428. current->net_xmit.skip_txqueue = skip;
  3429. }
  3430. EXPORT_SYMBOL_GPL(netdev_xmit_skip_txqueue);
  3431. #endif
  3432. #endif /* CONFIG_NET_EGRESS */
  3433. #ifdef CONFIG_NET_XGRESS
  3434. static int tc_run(struct tcx_entry *entry, struct sk_buff *skb,
  3435. enum skb_drop_reason *drop_reason)
  3436. {
  3437. int ret = TC_ACT_UNSPEC;
  3438. #ifdef CONFIG_NET_CLS_ACT
  3439. struct mini_Qdisc *miniq = rcu_dereference_bh(entry->miniq);
  3440. struct tcf_result res;
  3441. if (!miniq)
  3442. return ret;
  3443. /* Global bypass */
  3444. if (!static_branch_likely(&tcf_sw_enabled_key))
  3445. return ret;
  3446. /* Block-wise bypass */
  3447. if (tcf_block_bypass_sw(miniq->block))
  3448. return ret;
  3449. tc_skb_cb(skb)->mru = 0;
  3450. tc_skb_cb(skb)->post_ct = false;
  3451. tcf_set_drop_reason(skb, *drop_reason);
  3452. mini_qdisc_bstats_cpu_update(miniq, skb);
  3453. ret = tcf_classify(skb, miniq->block, miniq->filter_list, &res, false);
  3454. /* Only tcf related quirks below. */
  3455. switch (ret) {
  3456. case TC_ACT_SHOT:
  3457. *drop_reason = tcf_get_drop_reason(skb);
  3458. mini_qdisc_qstats_cpu_drop(miniq);
  3459. break;
  3460. case TC_ACT_OK:
  3461. case TC_ACT_RECLASSIFY:
  3462. skb->tc_index = TC_H_MIN(res.classid);
  3463. break;
  3464. }
  3465. #endif /* CONFIG_NET_CLS_ACT */
  3466. return ret;
  3467. }
  3468. static DEFINE_STATIC_KEY_FALSE(tcx_needed_key);
  3469. void tcx_inc(void)
  3470. {
  3471. static_branch_inc(&tcx_needed_key);
  3472. }
  3473. void tcx_dec(void)
  3474. {
  3475. static_branch_dec(&tcx_needed_key);
  3476. }
  3477. static __always_inline enum tcx_action_base
  3478. tcx_run(const struct bpf_mprog_entry *entry, struct sk_buff *skb,
  3479. const bool needs_mac)
  3480. {
  3481. const struct bpf_mprog_fp *fp;
  3482. const struct bpf_prog *prog;
  3483. int ret = TCX_NEXT;
  3484. if (needs_mac)
  3485. __skb_push(skb, skb->mac_len);
  3486. bpf_mprog_foreach_prog(entry, fp, prog) {
  3487. bpf_compute_data_pointers(skb);
  3488. ret = bpf_prog_run(prog, skb);
  3489. if (ret != TCX_NEXT)
  3490. break;
  3491. }
  3492. if (needs_mac)
  3493. __skb_pull(skb, skb->mac_len);
  3494. return tcx_action_code(skb, ret);
  3495. }
  3496. static __always_inline struct sk_buff *
  3497. sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
  3498. struct net_device *orig_dev, bool *another)
  3499. {
  3500. struct bpf_mprog_entry *entry = rcu_dereference_bh(skb->dev->tcx_ingress);
  3501. enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_INGRESS;
  3502. struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
  3503. int sch_ret;
  3504. if (!entry)
  3505. return skb;
  3506. bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
  3507. if (*pt_prev) {
  3508. *ret = deliver_skb(skb, *pt_prev, orig_dev);
  3509. *pt_prev = NULL;
  3510. }
  3511. qdisc_skb_cb(skb)->pkt_len = skb->len;
  3512. tcx_set_ingress(skb, true);
  3513. if (static_branch_unlikely(&tcx_needed_key)) {
  3514. sch_ret = tcx_run(entry, skb, true);
  3515. if (sch_ret != TC_ACT_UNSPEC)
  3516. goto ingress_verdict;
  3517. }
  3518. sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason);
  3519. ingress_verdict:
  3520. switch (sch_ret) {
  3521. case TC_ACT_REDIRECT:
  3522. /* skb_mac_header check was done by BPF, so we can safely
  3523. * push the L2 header back before redirecting to another
  3524. * netdev.
  3525. */
  3526. __skb_push(skb, skb->mac_len);
  3527. if (skb_do_redirect(skb) == -EAGAIN) {
  3528. __skb_pull(skb, skb->mac_len);
  3529. *another = true;
  3530. break;
  3531. }
  3532. *ret = NET_RX_SUCCESS;
  3533. bpf_net_ctx_clear(bpf_net_ctx);
  3534. return NULL;
  3535. case TC_ACT_SHOT:
  3536. kfree_skb_reason(skb, drop_reason);
  3537. *ret = NET_RX_DROP;
  3538. bpf_net_ctx_clear(bpf_net_ctx);
  3539. return NULL;
  3540. /* used by tc_run */
  3541. case TC_ACT_STOLEN:
  3542. case TC_ACT_QUEUED:
  3543. case TC_ACT_TRAP:
  3544. consume_skb(skb);
  3545. fallthrough;
  3546. case TC_ACT_CONSUMED:
  3547. *ret = NET_RX_SUCCESS;
  3548. bpf_net_ctx_clear(bpf_net_ctx);
  3549. return NULL;
  3550. }
  3551. bpf_net_ctx_clear(bpf_net_ctx);
  3552. return skb;
  3553. }
  3554. static __always_inline struct sk_buff *
  3555. sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
  3556. {
  3557. struct bpf_mprog_entry *entry = rcu_dereference_bh(dev->tcx_egress);
  3558. enum skb_drop_reason drop_reason = SKB_DROP_REASON_TC_EGRESS;
  3559. struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
  3560. int sch_ret;
  3561. if (!entry)
  3562. return skb;
  3563. bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
  3564. /* qdisc_skb_cb(skb)->pkt_len & tcx_set_ingress() was
  3565. * already set by the caller.
  3566. */
  3567. if (static_branch_unlikely(&tcx_needed_key)) {
  3568. sch_ret = tcx_run(entry, skb, false);
  3569. if (sch_ret != TC_ACT_UNSPEC)
  3570. goto egress_verdict;
  3571. }
  3572. sch_ret = tc_run(tcx_entry(entry), skb, &drop_reason);
  3573. egress_verdict:
  3574. switch (sch_ret) {
  3575. case TC_ACT_REDIRECT:
  3576. /* No need to push/pop skb's mac_header here on egress! */
  3577. skb_do_redirect(skb);
  3578. *ret = NET_XMIT_SUCCESS;
  3579. bpf_net_ctx_clear(bpf_net_ctx);
  3580. return NULL;
  3581. case TC_ACT_SHOT:
  3582. kfree_skb_reason(skb, drop_reason);
  3583. *ret = NET_XMIT_DROP;
  3584. bpf_net_ctx_clear(bpf_net_ctx);
  3585. return NULL;
  3586. /* used by tc_run */
  3587. case TC_ACT_STOLEN:
  3588. case TC_ACT_QUEUED:
  3589. case TC_ACT_TRAP:
  3590. consume_skb(skb);
  3591. fallthrough;
  3592. case TC_ACT_CONSUMED:
  3593. *ret = NET_XMIT_SUCCESS;
  3594. bpf_net_ctx_clear(bpf_net_ctx);
  3595. return NULL;
  3596. }
  3597. bpf_net_ctx_clear(bpf_net_ctx);
  3598. return skb;
  3599. }
  3600. #else
  3601. static __always_inline struct sk_buff *
  3602. sch_handle_ingress(struct sk_buff *skb, struct packet_type **pt_prev, int *ret,
  3603. struct net_device *orig_dev, bool *another)
  3604. {
  3605. return skb;
  3606. }
  3607. static __always_inline struct sk_buff *
  3608. sch_handle_egress(struct sk_buff *skb, int *ret, struct net_device *dev)
  3609. {
  3610. return skb;
  3611. }
  3612. #endif /* CONFIG_NET_XGRESS */
  3613. #ifdef CONFIG_XPS
  3614. static int __get_xps_queue_idx(struct net_device *dev, struct sk_buff *skb,
  3615. struct xps_dev_maps *dev_maps, unsigned int tci)
  3616. {
  3617. int tc = netdev_get_prio_tc_map(dev, skb->priority);
  3618. struct xps_map *map;
  3619. int queue_index = -1;
  3620. if (tc >= dev_maps->num_tc || tci >= dev_maps->nr_ids)
  3621. return queue_index;
  3622. tci *= dev_maps->num_tc;
  3623. tci += tc;
  3624. map = rcu_dereference(dev_maps->attr_map[tci]);
  3625. if (map) {
  3626. if (map->len == 1)
  3627. queue_index = map->queues[0];
  3628. else
  3629. queue_index = map->queues[reciprocal_scale(
  3630. skb_get_hash(skb), map->len)];
  3631. if (unlikely(queue_index >= dev->real_num_tx_queues))
  3632. queue_index = -1;
  3633. }
  3634. return queue_index;
  3635. }
  3636. #endif
  3637. static int get_xps_queue(struct net_device *dev, struct net_device *sb_dev,
  3638. struct sk_buff *skb)
  3639. {
  3640. #ifdef CONFIG_XPS
  3641. struct xps_dev_maps *dev_maps;
  3642. struct sock *sk = skb->sk;
  3643. int queue_index = -1;
  3644. if (!static_key_false(&xps_needed))
  3645. return -1;
  3646. rcu_read_lock();
  3647. if (!static_key_false(&xps_rxqs_needed))
  3648. goto get_cpus_map;
  3649. dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_RXQS]);
  3650. if (dev_maps) {
  3651. int tci = sk_rx_queue_get(sk);
  3652. if (tci >= 0)
  3653. queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
  3654. tci);
  3655. }
  3656. get_cpus_map:
  3657. if (queue_index < 0) {
  3658. dev_maps = rcu_dereference(sb_dev->xps_maps[XPS_CPUS]);
  3659. if (dev_maps) {
  3660. unsigned int tci = skb->sender_cpu - 1;
  3661. queue_index = __get_xps_queue_idx(dev, skb, dev_maps,
  3662. tci);
  3663. }
  3664. }
  3665. rcu_read_unlock();
  3666. return queue_index;
  3667. #else
  3668. return -1;
  3669. #endif
  3670. }
  3671. u16 dev_pick_tx_zero(struct net_device *dev, struct sk_buff *skb,
  3672. struct net_device *sb_dev)
  3673. {
  3674. return 0;
  3675. }
  3676. EXPORT_SYMBOL(dev_pick_tx_zero);
  3677. u16 netdev_pick_tx(struct net_device *dev, struct sk_buff *skb,
  3678. struct net_device *sb_dev)
  3679. {
  3680. struct sock *sk = skb->sk;
  3681. int queue_index = sk_tx_queue_get(sk);
  3682. sb_dev = sb_dev ? : dev;
  3683. if (queue_index < 0 || skb->ooo_okay ||
  3684. queue_index >= dev->real_num_tx_queues) {
  3685. int new_index = get_xps_queue(dev, sb_dev, skb);
  3686. if (new_index < 0)
  3687. new_index = skb_tx_hash(dev, sb_dev, skb);
  3688. if (queue_index != new_index && sk &&
  3689. sk_fullsock(sk) &&
  3690. rcu_access_pointer(sk->sk_dst_cache))
  3691. sk_tx_queue_set(sk, new_index);
  3692. queue_index = new_index;
  3693. }
  3694. return queue_index;
  3695. }
  3696. EXPORT_SYMBOL(netdev_pick_tx);
  3697. struct netdev_queue *netdev_core_pick_tx(struct net_device *dev,
  3698. struct sk_buff *skb,
  3699. struct net_device *sb_dev)
  3700. {
  3701. int queue_index = 0;
  3702. #ifdef CONFIG_XPS
  3703. u32 sender_cpu = skb->sender_cpu - 1;
  3704. if (sender_cpu >= (u32)NR_CPUS)
  3705. skb->sender_cpu = raw_smp_processor_id() + 1;
  3706. #endif
  3707. if (dev->real_num_tx_queues != 1) {
  3708. const struct net_device_ops *ops = dev->netdev_ops;
  3709. if (ops->ndo_select_queue)
  3710. queue_index = ops->ndo_select_queue(dev, skb, sb_dev);
  3711. else
  3712. queue_index = netdev_pick_tx(dev, skb, sb_dev);
  3713. queue_index = netdev_cap_txqueue(dev, queue_index);
  3714. }
  3715. skb_set_queue_mapping(skb, queue_index);
  3716. return netdev_get_tx_queue(dev, queue_index);
  3717. }
  3718. /**
  3719. * __dev_queue_xmit() - transmit a buffer
  3720. * @skb: buffer to transmit
  3721. * @sb_dev: suboordinate device used for L2 forwarding offload
  3722. *
  3723. * Queue a buffer for transmission to a network device. The caller must
  3724. * have set the device and priority and built the buffer before calling
  3725. * this function. The function can be called from an interrupt.
  3726. *
  3727. * When calling this method, interrupts MUST be enabled. This is because
  3728. * the BH enable code must have IRQs enabled so that it will not deadlock.
  3729. *
  3730. * Regardless of the return value, the skb is consumed, so it is currently
  3731. * difficult to retry a send to this method. (You can bump the ref count
  3732. * before sending to hold a reference for retry if you are careful.)
  3733. *
  3734. * Return:
  3735. * * 0 - buffer successfully transmitted
  3736. * * positive qdisc return code - NET_XMIT_DROP etc.
  3737. * * negative errno - other errors
  3738. */
  3739. int __dev_queue_xmit(struct sk_buff *skb, struct net_device *sb_dev)
  3740. {
  3741. struct net_device *dev = skb->dev;
  3742. struct netdev_queue *txq = NULL;
  3743. struct Qdisc *q;
  3744. int rc = -ENOMEM;
  3745. bool again = false;
  3746. skb_reset_mac_header(skb);
  3747. skb_assert_len(skb);
  3748. if (unlikely(skb_shinfo(skb)->tx_flags & SKBTX_SCHED_TSTAMP))
  3749. __skb_tstamp_tx(skb, NULL, NULL, skb->sk, SCM_TSTAMP_SCHED);
  3750. /* Disable soft irqs for various locks below. Also
  3751. * stops preemption for RCU.
  3752. */
  3753. rcu_read_lock_bh();
  3754. skb_update_prio(skb);
  3755. qdisc_pkt_len_init(skb);
  3756. tcx_set_ingress(skb, false);
  3757. #ifdef CONFIG_NET_EGRESS
  3758. if (static_branch_unlikely(&egress_needed_key)) {
  3759. if (nf_hook_egress_active()) {
  3760. skb = nf_hook_egress(skb, &rc, dev);
  3761. if (!skb)
  3762. goto out;
  3763. }
  3764. netdev_xmit_skip_txqueue(false);
  3765. nf_skip_egress(skb, true);
  3766. skb = sch_handle_egress(skb, &rc, dev);
  3767. if (!skb)
  3768. goto out;
  3769. nf_skip_egress(skb, false);
  3770. if (netdev_xmit_txqueue_skipped())
  3771. txq = netdev_tx_queue_mapping(dev, skb);
  3772. }
  3773. #endif
  3774. /* If device/qdisc don't need skb->dst, release it right now while
  3775. * its hot in this cpu cache.
  3776. */
  3777. if (dev->priv_flags & IFF_XMIT_DST_RELEASE)
  3778. skb_dst_drop(skb);
  3779. else
  3780. skb_dst_force(skb);
  3781. if (!txq)
  3782. txq = netdev_core_pick_tx(dev, skb, sb_dev);
  3783. q = rcu_dereference_bh(txq->qdisc);
  3784. trace_net_dev_queue(skb);
  3785. if (q->enqueue) {
  3786. rc = __dev_xmit_skb(skb, q, dev, txq);
  3787. goto out;
  3788. }
  3789. /* The device has no queue. Common case for software devices:
  3790. * loopback, all the sorts of tunnels...
  3791. * Really, it is unlikely that netif_tx_lock protection is necessary
  3792. * here. (f.e. loopback and IP tunnels are clean ignoring statistics
  3793. * counters.)
  3794. * However, it is possible, that they rely on protection
  3795. * made by us here.
  3796. * Check this and shot the lock. It is not prone from deadlocks.
  3797. *Either shot noqueue qdisc, it is even simpler 8)
  3798. */
  3799. if (dev->flags & IFF_UP) {
  3800. int cpu = smp_processor_id(); /* ok because BHs are off */
  3801. /* Other cpus might concurrently change txq->xmit_lock_owner
  3802. * to -1 or to their cpu id, but not to our id.
  3803. */
  3804. if (READ_ONCE(txq->xmit_lock_owner) != cpu) {
  3805. if (dev_xmit_recursion())
  3806. goto recursion_alert;
  3807. skb = validate_xmit_skb(skb, dev, &again);
  3808. if (!skb)
  3809. goto out;
  3810. HARD_TX_LOCK(dev, txq, cpu);
  3811. if (!netif_xmit_stopped(txq)) {
  3812. dev_xmit_recursion_inc();
  3813. skb = dev_hard_start_xmit(skb, dev, txq, &rc);
  3814. dev_xmit_recursion_dec();
  3815. if (dev_xmit_complete(rc)) {
  3816. HARD_TX_UNLOCK(dev, txq);
  3817. goto out;
  3818. }
  3819. }
  3820. HARD_TX_UNLOCK(dev, txq);
  3821. net_crit_ratelimited("Virtual device %s asks to queue packet!\n",
  3822. dev->name);
  3823. } else {
  3824. /* Recursion is detected! It is possible,
  3825. * unfortunately
  3826. */
  3827. recursion_alert:
  3828. net_crit_ratelimited("Dead loop on virtual device %s, fix it urgently!\n",
  3829. dev->name);
  3830. }
  3831. }
  3832. rc = -ENETDOWN;
  3833. rcu_read_unlock_bh();
  3834. dev_core_stats_tx_dropped_inc(dev);
  3835. kfree_skb_list(skb);
  3836. return rc;
  3837. out:
  3838. rcu_read_unlock_bh();
  3839. return rc;
  3840. }
  3841. EXPORT_SYMBOL(__dev_queue_xmit);
  3842. int __dev_direct_xmit(struct sk_buff *skb, u16 queue_id)
  3843. {
  3844. struct net_device *dev = skb->dev;
  3845. struct sk_buff *orig_skb = skb;
  3846. struct netdev_queue *txq;
  3847. int ret = NETDEV_TX_BUSY;
  3848. bool again = false;
  3849. if (unlikely(!netif_running(dev) ||
  3850. !netif_carrier_ok(dev)))
  3851. goto drop;
  3852. skb = validate_xmit_skb_list(skb, dev, &again);
  3853. if (skb != orig_skb)
  3854. goto drop;
  3855. skb_set_queue_mapping(skb, queue_id);
  3856. txq = skb_get_tx_queue(dev, skb);
  3857. local_bh_disable();
  3858. dev_xmit_recursion_inc();
  3859. HARD_TX_LOCK(dev, txq, smp_processor_id());
  3860. if (!netif_xmit_frozen_or_drv_stopped(txq))
  3861. ret = netdev_start_xmit(skb, dev, txq, false);
  3862. HARD_TX_UNLOCK(dev, txq);
  3863. dev_xmit_recursion_dec();
  3864. local_bh_enable();
  3865. return ret;
  3866. drop:
  3867. dev_core_stats_tx_dropped_inc(dev);
  3868. kfree_skb_list(skb);
  3869. return NET_XMIT_DROP;
  3870. }
  3871. EXPORT_SYMBOL(__dev_direct_xmit);
  3872. /*************************************************************************
  3873. * Receiver routines
  3874. *************************************************************************/
  3875. static DEFINE_PER_CPU(struct task_struct *, backlog_napi);
  3876. int weight_p __read_mostly = 64; /* old backlog weight */
  3877. int dev_weight_rx_bias __read_mostly = 1; /* bias for backlog weight */
  3878. int dev_weight_tx_bias __read_mostly = 1; /* bias for output_queue quota */
  3879. /* Called with irq disabled */
  3880. static inline void ____napi_schedule(struct softnet_data *sd,
  3881. struct napi_struct *napi)
  3882. {
  3883. struct task_struct *thread;
  3884. lockdep_assert_irqs_disabled();
  3885. if (test_bit(NAPI_STATE_THREADED, &napi->state)) {
  3886. /* Paired with smp_mb__before_atomic() in
  3887. * napi_enable()/dev_set_threaded().
  3888. * Use READ_ONCE() to guarantee a complete
  3889. * read on napi->thread. Only call
  3890. * wake_up_process() when it's not NULL.
  3891. */
  3892. thread = READ_ONCE(napi->thread);
  3893. if (thread) {
  3894. if (use_backlog_threads() && thread == raw_cpu_read(backlog_napi))
  3895. goto use_local_napi;
  3896. set_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
  3897. wake_up_process(thread);
  3898. return;
  3899. }
  3900. }
  3901. use_local_napi:
  3902. list_add_tail(&napi->poll_list, &sd->poll_list);
  3903. WRITE_ONCE(napi->list_owner, smp_processor_id());
  3904. /* If not called from net_rx_action()
  3905. * we have to raise NET_RX_SOFTIRQ.
  3906. */
  3907. if (!sd->in_net_rx_action)
  3908. raise_softirq_irqoff(NET_RX_SOFTIRQ);
  3909. }
  3910. #ifdef CONFIG_RPS
  3911. struct static_key_false rps_needed __read_mostly;
  3912. EXPORT_SYMBOL(rps_needed);
  3913. struct static_key_false rfs_needed __read_mostly;
  3914. EXPORT_SYMBOL(rfs_needed);
  3915. static struct rps_dev_flow *
  3916. set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
  3917. struct rps_dev_flow *rflow, u16 next_cpu)
  3918. {
  3919. if (next_cpu < nr_cpu_ids) {
  3920. u32 head;
  3921. #ifdef CONFIG_RFS_ACCEL
  3922. struct netdev_rx_queue *rxqueue;
  3923. struct rps_dev_flow_table *flow_table;
  3924. struct rps_dev_flow *old_rflow;
  3925. u16 rxq_index;
  3926. u32 flow_id;
  3927. int rc;
  3928. /* Should we steer this flow to a different hardware queue? */
  3929. if (!skb_rx_queue_recorded(skb) || !dev->rx_cpu_rmap ||
  3930. !(dev->features & NETIF_F_NTUPLE))
  3931. goto out;
  3932. rxq_index = cpu_rmap_lookup_index(dev->rx_cpu_rmap, next_cpu);
  3933. if (rxq_index == skb_get_rx_queue(skb))
  3934. goto out;
  3935. rxqueue = dev->_rx + rxq_index;
  3936. flow_table = rcu_dereference(rxqueue->rps_flow_table);
  3937. if (!flow_table)
  3938. goto out;
  3939. flow_id = skb_get_hash(skb) & flow_table->mask;
  3940. rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
  3941. rxq_index, flow_id);
  3942. if (rc < 0)
  3943. goto out;
  3944. old_rflow = rflow;
  3945. rflow = &flow_table->flows[flow_id];
  3946. WRITE_ONCE(rflow->filter, rc);
  3947. if (old_rflow->filter == rc)
  3948. WRITE_ONCE(old_rflow->filter, RPS_NO_FILTER);
  3949. out:
  3950. #endif
  3951. head = READ_ONCE(per_cpu(softnet_data, next_cpu).input_queue_head);
  3952. rps_input_queue_tail_save(&rflow->last_qtail, head);
  3953. }
  3954. WRITE_ONCE(rflow->cpu, next_cpu);
  3955. return rflow;
  3956. }
  3957. /*
  3958. * get_rps_cpu is called from netif_receive_skb and returns the target
  3959. * CPU from the RPS map of the receiving queue for a given skb.
  3960. * rcu_read_lock must be held on entry.
  3961. */
  3962. static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
  3963. struct rps_dev_flow **rflowp)
  3964. {
  3965. const struct rps_sock_flow_table *sock_flow_table;
  3966. struct netdev_rx_queue *rxqueue = dev->_rx;
  3967. struct rps_dev_flow_table *flow_table;
  3968. struct rps_map *map;
  3969. int cpu = -1;
  3970. u32 tcpu;
  3971. u32 hash;
  3972. if (skb_rx_queue_recorded(skb)) {
  3973. u16 index = skb_get_rx_queue(skb);
  3974. if (unlikely(index >= dev->real_num_rx_queues)) {
  3975. WARN_ONCE(dev->real_num_rx_queues > 1,
  3976. "%s received packet on queue %u, but number "
  3977. "of RX queues is %u\n",
  3978. dev->name, index, dev->real_num_rx_queues);
  3979. goto done;
  3980. }
  3981. rxqueue += index;
  3982. }
  3983. /* Avoid computing hash if RFS/RPS is not active for this rxqueue */
  3984. flow_table = rcu_dereference(rxqueue->rps_flow_table);
  3985. map = rcu_dereference(rxqueue->rps_map);
  3986. if (!flow_table && !map)
  3987. goto done;
  3988. skb_reset_network_header(skb);
  3989. hash = skb_get_hash(skb);
  3990. if (!hash)
  3991. goto done;
  3992. sock_flow_table = rcu_dereference(net_hotdata.rps_sock_flow_table);
  3993. if (flow_table && sock_flow_table) {
  3994. struct rps_dev_flow *rflow;
  3995. u32 next_cpu;
  3996. u32 ident;
  3997. /* First check into global flow table if there is a match.
  3998. * This READ_ONCE() pairs with WRITE_ONCE() from rps_record_sock_flow().
  3999. */
  4000. ident = READ_ONCE(sock_flow_table->ents[hash & sock_flow_table->mask]);
  4001. if ((ident ^ hash) & ~net_hotdata.rps_cpu_mask)
  4002. goto try_rps;
  4003. next_cpu = ident & net_hotdata.rps_cpu_mask;
  4004. /* OK, now we know there is a match,
  4005. * we can look at the local (per receive queue) flow table
  4006. */
  4007. rflow = &flow_table->flows[hash & flow_table->mask];
  4008. tcpu = rflow->cpu;
  4009. /*
  4010. * If the desired CPU (where last recvmsg was done) is
  4011. * different from current CPU (one in the rx-queue flow
  4012. * table entry), switch if one of the following holds:
  4013. * - Current CPU is unset (>= nr_cpu_ids).
  4014. * - Current CPU is offline.
  4015. * - The current CPU's queue tail has advanced beyond the
  4016. * last packet that was enqueued using this table entry.
  4017. * This guarantees that all previous packets for the flow
  4018. * have been dequeued, thus preserving in order delivery.
  4019. */
  4020. if (unlikely(tcpu != next_cpu) &&
  4021. (tcpu >= nr_cpu_ids || !cpu_online(tcpu) ||
  4022. ((int)(READ_ONCE(per_cpu(softnet_data, tcpu).input_queue_head) -
  4023. rflow->last_qtail)) >= 0)) {
  4024. tcpu = next_cpu;
  4025. rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
  4026. }
  4027. if (tcpu < nr_cpu_ids && cpu_online(tcpu)) {
  4028. *rflowp = rflow;
  4029. cpu = tcpu;
  4030. goto done;
  4031. }
  4032. }
  4033. try_rps:
  4034. if (map) {
  4035. tcpu = map->cpus[reciprocal_scale(hash, map->len)];
  4036. if (cpu_online(tcpu)) {
  4037. cpu = tcpu;
  4038. goto done;
  4039. }
  4040. }
  4041. done:
  4042. return cpu;
  4043. }
  4044. #ifdef CONFIG_RFS_ACCEL
  4045. /**
  4046. * rps_may_expire_flow - check whether an RFS hardware filter may be removed
  4047. * @dev: Device on which the filter was set
  4048. * @rxq_index: RX queue index
  4049. * @flow_id: Flow ID passed to ndo_rx_flow_steer()
  4050. * @filter_id: Filter ID returned by ndo_rx_flow_steer()
  4051. *
  4052. * Drivers that implement ndo_rx_flow_steer() should periodically call
  4053. * this function for each installed filter and remove the filters for
  4054. * which it returns %true.
  4055. */
  4056. bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
  4057. u32 flow_id, u16 filter_id)
  4058. {
  4059. struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
  4060. struct rps_dev_flow_table *flow_table;
  4061. struct rps_dev_flow *rflow;
  4062. bool expire = true;
  4063. unsigned int cpu;
  4064. rcu_read_lock();
  4065. flow_table = rcu_dereference(rxqueue->rps_flow_table);
  4066. if (flow_table && flow_id <= flow_table->mask) {
  4067. rflow = &flow_table->flows[flow_id];
  4068. cpu = READ_ONCE(rflow->cpu);
  4069. if (READ_ONCE(rflow->filter) == filter_id && cpu < nr_cpu_ids &&
  4070. ((int)(READ_ONCE(per_cpu(softnet_data, cpu).input_queue_head) -
  4071. READ_ONCE(rflow->last_qtail)) <
  4072. (int)(10 * flow_table->mask)))
  4073. expire = false;
  4074. }
  4075. rcu_read_unlock();
  4076. return expire;
  4077. }
  4078. EXPORT_SYMBOL(rps_may_expire_flow);
  4079. #endif /* CONFIG_RFS_ACCEL */
  4080. /* Called from hardirq (IPI) context */
  4081. static void rps_trigger_softirq(void *data)
  4082. {
  4083. struct softnet_data *sd = data;
  4084. ____napi_schedule(sd, &sd->backlog);
  4085. sd->received_rps++;
  4086. }
  4087. #endif /* CONFIG_RPS */
  4088. /* Called from hardirq (IPI) context */
  4089. static void trigger_rx_softirq(void *data)
  4090. {
  4091. struct softnet_data *sd = data;
  4092. __raise_softirq_irqoff(NET_RX_SOFTIRQ);
  4093. smp_store_release(&sd->defer_ipi_scheduled, 0);
  4094. }
  4095. /*
  4096. * After we queued a packet into sd->input_pkt_queue,
  4097. * we need to make sure this queue is serviced soon.
  4098. *
  4099. * - If this is another cpu queue, link it to our rps_ipi_list,
  4100. * and make sure we will process rps_ipi_list from net_rx_action().
  4101. *
  4102. * - If this is our own queue, NAPI schedule our backlog.
  4103. * Note that this also raises NET_RX_SOFTIRQ.
  4104. */
  4105. static void napi_schedule_rps(struct softnet_data *sd)
  4106. {
  4107. struct softnet_data *mysd = this_cpu_ptr(&softnet_data);
  4108. #ifdef CONFIG_RPS
  4109. if (sd != mysd) {
  4110. if (use_backlog_threads()) {
  4111. __napi_schedule_irqoff(&sd->backlog);
  4112. return;
  4113. }
  4114. sd->rps_ipi_next = mysd->rps_ipi_list;
  4115. mysd->rps_ipi_list = sd;
  4116. /* If not called from net_rx_action() or napi_threaded_poll()
  4117. * we have to raise NET_RX_SOFTIRQ.
  4118. */
  4119. if (!mysd->in_net_rx_action && !mysd->in_napi_threaded_poll)
  4120. __raise_softirq_irqoff(NET_RX_SOFTIRQ);
  4121. return;
  4122. }
  4123. #endif /* CONFIG_RPS */
  4124. __napi_schedule_irqoff(&mysd->backlog);
  4125. }
  4126. void kick_defer_list_purge(struct softnet_data *sd, unsigned int cpu)
  4127. {
  4128. unsigned long flags;
  4129. if (use_backlog_threads()) {
  4130. backlog_lock_irq_save(sd, &flags);
  4131. if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state))
  4132. __napi_schedule_irqoff(&sd->backlog);
  4133. backlog_unlock_irq_restore(sd, &flags);
  4134. } else if (!cmpxchg(&sd->defer_ipi_scheduled, 0, 1)) {
  4135. smp_call_function_single_async(cpu, &sd->defer_csd);
  4136. }
  4137. }
  4138. #ifdef CONFIG_NET_FLOW_LIMIT
  4139. int netdev_flow_limit_table_len __read_mostly = (1 << 12);
  4140. #endif
  4141. static bool skb_flow_limit(struct sk_buff *skb, unsigned int qlen)
  4142. {
  4143. #ifdef CONFIG_NET_FLOW_LIMIT
  4144. struct sd_flow_limit *fl;
  4145. struct softnet_data *sd;
  4146. unsigned int old_flow, new_flow;
  4147. if (qlen < (READ_ONCE(net_hotdata.max_backlog) >> 1))
  4148. return false;
  4149. sd = this_cpu_ptr(&softnet_data);
  4150. rcu_read_lock();
  4151. fl = rcu_dereference(sd->flow_limit);
  4152. if (fl) {
  4153. new_flow = skb_get_hash(skb) & (fl->num_buckets - 1);
  4154. old_flow = fl->history[fl->history_head];
  4155. fl->history[fl->history_head] = new_flow;
  4156. fl->history_head++;
  4157. fl->history_head &= FLOW_LIMIT_HISTORY - 1;
  4158. if (likely(fl->buckets[old_flow]))
  4159. fl->buckets[old_flow]--;
  4160. if (++fl->buckets[new_flow] > (FLOW_LIMIT_HISTORY >> 1)) {
  4161. fl->count++;
  4162. rcu_read_unlock();
  4163. return true;
  4164. }
  4165. }
  4166. rcu_read_unlock();
  4167. #endif
  4168. return false;
  4169. }
  4170. /*
  4171. * enqueue_to_backlog is called to queue an skb to a per CPU backlog
  4172. * queue (may be a remote CPU queue).
  4173. */
  4174. static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
  4175. unsigned int *qtail)
  4176. {
  4177. enum skb_drop_reason reason;
  4178. struct softnet_data *sd;
  4179. unsigned long flags;
  4180. unsigned int qlen;
  4181. int max_backlog;
  4182. u32 tail;
  4183. reason = SKB_DROP_REASON_DEV_READY;
  4184. if (!netif_running(skb->dev))
  4185. goto bad_dev;
  4186. reason = SKB_DROP_REASON_CPU_BACKLOG;
  4187. sd = &per_cpu(softnet_data, cpu);
  4188. qlen = skb_queue_len_lockless(&sd->input_pkt_queue);
  4189. max_backlog = READ_ONCE(net_hotdata.max_backlog);
  4190. if (unlikely(qlen > max_backlog))
  4191. goto cpu_backlog_drop;
  4192. backlog_lock_irq_save(sd, &flags);
  4193. qlen = skb_queue_len(&sd->input_pkt_queue);
  4194. if (qlen <= max_backlog && !skb_flow_limit(skb, qlen)) {
  4195. if (!qlen) {
  4196. /* Schedule NAPI for backlog device. We can use
  4197. * non atomic operation as we own the queue lock.
  4198. */
  4199. if (!__test_and_set_bit(NAPI_STATE_SCHED,
  4200. &sd->backlog.state))
  4201. napi_schedule_rps(sd);
  4202. }
  4203. __skb_queue_tail(&sd->input_pkt_queue, skb);
  4204. tail = rps_input_queue_tail_incr(sd);
  4205. backlog_unlock_irq_restore(sd, &flags);
  4206. /* save the tail outside of the critical section */
  4207. rps_input_queue_tail_save(qtail, tail);
  4208. return NET_RX_SUCCESS;
  4209. }
  4210. backlog_unlock_irq_restore(sd, &flags);
  4211. cpu_backlog_drop:
  4212. atomic_inc(&sd->dropped);
  4213. bad_dev:
  4214. dev_core_stats_rx_dropped_inc(skb->dev);
  4215. kfree_skb_reason(skb, reason);
  4216. return NET_RX_DROP;
  4217. }
  4218. static struct netdev_rx_queue *netif_get_rxqueue(struct sk_buff *skb)
  4219. {
  4220. struct net_device *dev = skb->dev;
  4221. struct netdev_rx_queue *rxqueue;
  4222. rxqueue = dev->_rx;
  4223. if (skb_rx_queue_recorded(skb)) {
  4224. u16 index = skb_get_rx_queue(skb);
  4225. if (unlikely(index >= dev->real_num_rx_queues)) {
  4226. WARN_ONCE(dev->real_num_rx_queues > 1,
  4227. "%s received packet on queue %u, but number "
  4228. "of RX queues is %u\n",
  4229. dev->name, index, dev->real_num_rx_queues);
  4230. return rxqueue; /* Return first rxqueue */
  4231. }
  4232. rxqueue += index;
  4233. }
  4234. return rxqueue;
  4235. }
  4236. u32 bpf_prog_run_generic_xdp(struct sk_buff *skb, struct xdp_buff *xdp,
  4237. struct bpf_prog *xdp_prog)
  4238. {
  4239. void *orig_data, *orig_data_end, *hard_start;
  4240. struct netdev_rx_queue *rxqueue;
  4241. bool orig_bcast, orig_host;
  4242. u32 mac_len, frame_sz;
  4243. __be16 orig_eth_type;
  4244. struct ethhdr *eth;
  4245. u32 metalen, act;
  4246. int off;
  4247. /* The XDP program wants to see the packet starting at the MAC
  4248. * header.
  4249. */
  4250. mac_len = skb->data - skb_mac_header(skb);
  4251. hard_start = skb->data - skb_headroom(skb);
  4252. /* SKB "head" area always have tailroom for skb_shared_info */
  4253. frame_sz = (void *)skb_end_pointer(skb) - hard_start;
  4254. frame_sz += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
  4255. rxqueue = netif_get_rxqueue(skb);
  4256. xdp_init_buff(xdp, frame_sz, &rxqueue->xdp_rxq);
  4257. xdp_prepare_buff(xdp, hard_start, skb_headroom(skb) - mac_len,
  4258. skb_headlen(skb) + mac_len, true);
  4259. if (skb_is_nonlinear(skb)) {
  4260. skb_shinfo(skb)->xdp_frags_size = skb->data_len;
  4261. xdp_buff_set_frags_flag(xdp);
  4262. } else {
  4263. xdp_buff_clear_frags_flag(xdp);
  4264. }
  4265. orig_data_end = xdp->data_end;
  4266. orig_data = xdp->data;
  4267. eth = (struct ethhdr *)xdp->data;
  4268. orig_host = ether_addr_equal_64bits(eth->h_dest, skb->dev->dev_addr);
  4269. orig_bcast = is_multicast_ether_addr_64bits(eth->h_dest);
  4270. orig_eth_type = eth->h_proto;
  4271. act = bpf_prog_run_xdp(xdp_prog, xdp);
  4272. /* check if bpf_xdp_adjust_head was used */
  4273. off = xdp->data - orig_data;
  4274. if (off) {
  4275. if (off > 0)
  4276. __skb_pull(skb, off);
  4277. else if (off < 0)
  4278. __skb_push(skb, -off);
  4279. skb->mac_header += off;
  4280. skb_reset_network_header(skb);
  4281. }
  4282. /* check if bpf_xdp_adjust_tail was used */
  4283. off = xdp->data_end - orig_data_end;
  4284. if (off != 0) {
  4285. skb_set_tail_pointer(skb, xdp->data_end - xdp->data);
  4286. skb->len += off; /* positive on grow, negative on shrink */
  4287. }
  4288. /* XDP frag metadata (e.g. nr_frags) are updated in eBPF helpers
  4289. * (e.g. bpf_xdp_adjust_tail), we need to update data_len here.
  4290. */
  4291. if (xdp_buff_has_frags(xdp))
  4292. skb->data_len = skb_shinfo(skb)->xdp_frags_size;
  4293. else
  4294. skb->data_len = 0;
  4295. /* check if XDP changed eth hdr such SKB needs update */
  4296. eth = (struct ethhdr *)xdp->data;
  4297. if ((orig_eth_type != eth->h_proto) ||
  4298. (orig_host != ether_addr_equal_64bits(eth->h_dest,
  4299. skb->dev->dev_addr)) ||
  4300. (orig_bcast != is_multicast_ether_addr_64bits(eth->h_dest))) {
  4301. __skb_push(skb, ETH_HLEN);
  4302. skb->pkt_type = PACKET_HOST;
  4303. skb->protocol = eth_type_trans(skb, skb->dev);
  4304. }
  4305. /* Redirect/Tx gives L2 packet, code that will reuse skb must __skb_pull
  4306. * before calling us again on redirect path. We do not call do_redirect
  4307. * as we leave that up to the caller.
  4308. *
  4309. * Caller is responsible for managing lifetime of skb (i.e. calling
  4310. * kfree_skb in response to actions it cannot handle/XDP_DROP).
  4311. */
  4312. switch (act) {
  4313. case XDP_REDIRECT:
  4314. case XDP_TX:
  4315. __skb_push(skb, mac_len);
  4316. break;
  4317. case XDP_PASS:
  4318. metalen = xdp->data - xdp->data_meta;
  4319. if (metalen)
  4320. skb_metadata_set(skb, metalen);
  4321. break;
  4322. }
  4323. return act;
  4324. }
  4325. static int
  4326. netif_skb_check_for_xdp(struct sk_buff **pskb, struct bpf_prog *prog)
  4327. {
  4328. struct sk_buff *skb = *pskb;
  4329. int err, hroom, troom;
  4330. if (!skb_cow_data_for_xdp(this_cpu_read(system_page_pool), pskb, prog))
  4331. return 0;
  4332. /* In case we have to go down the path and also linearize,
  4333. * then lets do the pskb_expand_head() work just once here.
  4334. */
  4335. hroom = XDP_PACKET_HEADROOM - skb_headroom(skb);
  4336. troom = skb->tail + skb->data_len - skb->end;
  4337. err = pskb_expand_head(skb,
  4338. hroom > 0 ? ALIGN(hroom, NET_SKB_PAD) : 0,
  4339. troom > 0 ? troom + 128 : 0, GFP_ATOMIC);
  4340. if (err)
  4341. return err;
  4342. return skb_linearize(skb);
  4343. }
  4344. static u32 netif_receive_generic_xdp(struct sk_buff **pskb,
  4345. struct xdp_buff *xdp,
  4346. struct bpf_prog *xdp_prog)
  4347. {
  4348. struct sk_buff *skb = *pskb;
  4349. u32 mac_len, act = XDP_DROP;
  4350. /* Reinjected packets coming from act_mirred or similar should
  4351. * not get XDP generic processing.
  4352. */
  4353. if (skb_is_redirected(skb))
  4354. return XDP_PASS;
  4355. /* XDP packets must have sufficient headroom of XDP_PACKET_HEADROOM
  4356. * bytes. This is the guarantee that also native XDP provides,
  4357. * thus we need to do it here as well.
  4358. */
  4359. mac_len = skb->data - skb_mac_header(skb);
  4360. __skb_push(skb, mac_len);
  4361. if (skb_cloned(skb) || skb_is_nonlinear(skb) ||
  4362. skb_headroom(skb) < XDP_PACKET_HEADROOM) {
  4363. if (netif_skb_check_for_xdp(pskb, xdp_prog))
  4364. goto do_drop;
  4365. }
  4366. __skb_pull(*pskb, mac_len);
  4367. act = bpf_prog_run_generic_xdp(*pskb, xdp, xdp_prog);
  4368. switch (act) {
  4369. case XDP_REDIRECT:
  4370. case XDP_TX:
  4371. case XDP_PASS:
  4372. break;
  4373. default:
  4374. bpf_warn_invalid_xdp_action((*pskb)->dev, xdp_prog, act);
  4375. fallthrough;
  4376. case XDP_ABORTED:
  4377. trace_xdp_exception((*pskb)->dev, xdp_prog, act);
  4378. fallthrough;
  4379. case XDP_DROP:
  4380. do_drop:
  4381. kfree_skb(*pskb);
  4382. break;
  4383. }
  4384. return act;
  4385. }
  4386. /* When doing generic XDP we have to bypass the qdisc layer and the
  4387. * network taps in order to match in-driver-XDP behavior. This also means
  4388. * that XDP packets are able to starve other packets going through a qdisc,
  4389. * and DDOS attacks will be more effective. In-driver-XDP use dedicated TX
  4390. * queues, so they do not have this starvation issue.
  4391. */
  4392. void generic_xdp_tx(struct sk_buff *skb, struct bpf_prog *xdp_prog)
  4393. {
  4394. struct net_device *dev = skb->dev;
  4395. struct netdev_queue *txq;
  4396. bool free_skb = true;
  4397. int cpu, rc;
  4398. txq = netdev_core_pick_tx(dev, skb, NULL);
  4399. cpu = smp_processor_id();
  4400. HARD_TX_LOCK(dev, txq, cpu);
  4401. if (!netif_xmit_frozen_or_drv_stopped(txq)) {
  4402. rc = netdev_start_xmit(skb, dev, txq, 0);
  4403. if (dev_xmit_complete(rc))
  4404. free_skb = false;
  4405. }
  4406. HARD_TX_UNLOCK(dev, txq);
  4407. if (free_skb) {
  4408. trace_xdp_exception(dev, xdp_prog, XDP_TX);
  4409. dev_core_stats_tx_dropped_inc(dev);
  4410. kfree_skb(skb);
  4411. }
  4412. }
  4413. static DEFINE_STATIC_KEY_FALSE(generic_xdp_needed_key);
  4414. int do_xdp_generic(struct bpf_prog *xdp_prog, struct sk_buff **pskb)
  4415. {
  4416. struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
  4417. if (xdp_prog) {
  4418. struct xdp_buff xdp;
  4419. u32 act;
  4420. int err;
  4421. bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
  4422. act = netif_receive_generic_xdp(pskb, &xdp, xdp_prog);
  4423. if (act != XDP_PASS) {
  4424. switch (act) {
  4425. case XDP_REDIRECT:
  4426. err = xdp_do_generic_redirect((*pskb)->dev, *pskb,
  4427. &xdp, xdp_prog);
  4428. if (err)
  4429. goto out_redir;
  4430. break;
  4431. case XDP_TX:
  4432. generic_xdp_tx(*pskb, xdp_prog);
  4433. break;
  4434. }
  4435. bpf_net_ctx_clear(bpf_net_ctx);
  4436. return XDP_DROP;
  4437. }
  4438. bpf_net_ctx_clear(bpf_net_ctx);
  4439. }
  4440. return XDP_PASS;
  4441. out_redir:
  4442. bpf_net_ctx_clear(bpf_net_ctx);
  4443. kfree_skb_reason(*pskb, SKB_DROP_REASON_XDP);
  4444. return XDP_DROP;
  4445. }
  4446. EXPORT_SYMBOL_GPL(do_xdp_generic);
  4447. static int netif_rx_internal(struct sk_buff *skb)
  4448. {
  4449. int ret;
  4450. net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb);
  4451. trace_netif_rx(skb);
  4452. #ifdef CONFIG_RPS
  4453. if (static_branch_unlikely(&rps_needed)) {
  4454. struct rps_dev_flow voidflow, *rflow = &voidflow;
  4455. int cpu;
  4456. rcu_read_lock();
  4457. cpu = get_rps_cpu(skb->dev, skb, &rflow);
  4458. if (cpu < 0)
  4459. cpu = smp_processor_id();
  4460. ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
  4461. rcu_read_unlock();
  4462. } else
  4463. #endif
  4464. {
  4465. unsigned int qtail;
  4466. ret = enqueue_to_backlog(skb, smp_processor_id(), &qtail);
  4467. }
  4468. return ret;
  4469. }
  4470. /**
  4471. * __netif_rx - Slightly optimized version of netif_rx
  4472. * @skb: buffer to post
  4473. *
  4474. * This behaves as netif_rx except that it does not disable bottom halves.
  4475. * As a result this function may only be invoked from the interrupt context
  4476. * (either hard or soft interrupt).
  4477. */
  4478. int __netif_rx(struct sk_buff *skb)
  4479. {
  4480. int ret;
  4481. lockdep_assert_once(hardirq_count() | softirq_count());
  4482. trace_netif_rx_entry(skb);
  4483. ret = netif_rx_internal(skb);
  4484. trace_netif_rx_exit(ret);
  4485. return ret;
  4486. }
  4487. EXPORT_SYMBOL(__netif_rx);
  4488. /**
  4489. * netif_rx - post buffer to the network code
  4490. * @skb: buffer to post
  4491. *
  4492. * This function receives a packet from a device driver and queues it for
  4493. * the upper (protocol) levels to process via the backlog NAPI device. It
  4494. * always succeeds. The buffer may be dropped during processing for
  4495. * congestion control or by the protocol layers.
  4496. * The network buffer is passed via the backlog NAPI device. Modern NIC
  4497. * driver should use NAPI and GRO.
  4498. * This function can used from interrupt and from process context. The
  4499. * caller from process context must not disable interrupts before invoking
  4500. * this function.
  4501. *
  4502. * return values:
  4503. * NET_RX_SUCCESS (no congestion)
  4504. * NET_RX_DROP (packet was dropped)
  4505. *
  4506. */
  4507. int netif_rx(struct sk_buff *skb)
  4508. {
  4509. bool need_bh_off = !(hardirq_count() | softirq_count());
  4510. int ret;
  4511. if (need_bh_off)
  4512. local_bh_disable();
  4513. trace_netif_rx_entry(skb);
  4514. ret = netif_rx_internal(skb);
  4515. trace_netif_rx_exit(ret);
  4516. if (need_bh_off)
  4517. local_bh_enable();
  4518. return ret;
  4519. }
  4520. EXPORT_SYMBOL(netif_rx);
  4521. static __latent_entropy void net_tx_action(void)
  4522. {
  4523. struct softnet_data *sd = this_cpu_ptr(&softnet_data);
  4524. if (sd->completion_queue) {
  4525. struct sk_buff *clist;
  4526. local_irq_disable();
  4527. clist = sd->completion_queue;
  4528. sd->completion_queue = NULL;
  4529. local_irq_enable();
  4530. while (clist) {
  4531. struct sk_buff *skb = clist;
  4532. clist = clist->next;
  4533. WARN_ON(refcount_read(&skb->users));
  4534. if (likely(get_kfree_skb_cb(skb)->reason == SKB_CONSUMED))
  4535. trace_consume_skb(skb, net_tx_action);
  4536. else
  4537. trace_kfree_skb(skb, net_tx_action,
  4538. get_kfree_skb_cb(skb)->reason, NULL);
  4539. if (skb->fclone != SKB_FCLONE_UNAVAILABLE)
  4540. __kfree_skb(skb);
  4541. else
  4542. __napi_kfree_skb(skb,
  4543. get_kfree_skb_cb(skb)->reason);
  4544. }
  4545. }
  4546. if (sd->output_queue) {
  4547. struct Qdisc *head;
  4548. local_irq_disable();
  4549. head = sd->output_queue;
  4550. sd->output_queue = NULL;
  4551. sd->output_queue_tailp = &sd->output_queue;
  4552. local_irq_enable();
  4553. rcu_read_lock();
  4554. while (head) {
  4555. struct Qdisc *q = head;
  4556. spinlock_t *root_lock = NULL;
  4557. head = head->next_sched;
  4558. /* We need to make sure head->next_sched is read
  4559. * before clearing __QDISC_STATE_SCHED
  4560. */
  4561. smp_mb__before_atomic();
  4562. if (!(q->flags & TCQ_F_NOLOCK)) {
  4563. root_lock = qdisc_lock(q);
  4564. spin_lock(root_lock);
  4565. } else if (unlikely(test_bit(__QDISC_STATE_DEACTIVATED,
  4566. &q->state))) {
  4567. /* There is a synchronize_net() between
  4568. * STATE_DEACTIVATED flag being set and
  4569. * qdisc_reset()/some_qdisc_is_busy() in
  4570. * dev_deactivate(), so we can safely bail out
  4571. * early here to avoid data race between
  4572. * qdisc_deactivate() and some_qdisc_is_busy()
  4573. * for lockless qdisc.
  4574. */
  4575. clear_bit(__QDISC_STATE_SCHED, &q->state);
  4576. continue;
  4577. }
  4578. clear_bit(__QDISC_STATE_SCHED, &q->state);
  4579. qdisc_run(q);
  4580. if (root_lock)
  4581. spin_unlock(root_lock);
  4582. }
  4583. rcu_read_unlock();
  4584. }
  4585. xfrm_dev_backlog(sd);
  4586. }
  4587. #if IS_ENABLED(CONFIG_BRIDGE) && IS_ENABLED(CONFIG_ATM_LANE)
  4588. /* This hook is defined here for ATM LANE */
  4589. int (*br_fdb_test_addr_hook)(struct net_device *dev,
  4590. unsigned char *addr) __read_mostly;
  4591. EXPORT_SYMBOL_GPL(br_fdb_test_addr_hook);
  4592. #endif
  4593. /**
  4594. * netdev_is_rx_handler_busy - check if receive handler is registered
  4595. * @dev: device to check
  4596. *
  4597. * Check if a receive handler is already registered for a given device.
  4598. * Return true if there one.
  4599. *
  4600. * The caller must hold the rtnl_mutex.
  4601. */
  4602. bool netdev_is_rx_handler_busy(struct net_device *dev)
  4603. {
  4604. ASSERT_RTNL();
  4605. return dev && rtnl_dereference(dev->rx_handler);
  4606. }
  4607. EXPORT_SYMBOL_GPL(netdev_is_rx_handler_busy);
  4608. /**
  4609. * netdev_rx_handler_register - register receive handler
  4610. * @dev: device to register a handler for
  4611. * @rx_handler: receive handler to register
  4612. * @rx_handler_data: data pointer that is used by rx handler
  4613. *
  4614. * Register a receive handler for a device. This handler will then be
  4615. * called from __netif_receive_skb. A negative errno code is returned
  4616. * on a failure.
  4617. *
  4618. * The caller must hold the rtnl_mutex.
  4619. *
  4620. * For a general description of rx_handler, see enum rx_handler_result.
  4621. */
  4622. int netdev_rx_handler_register(struct net_device *dev,
  4623. rx_handler_func_t *rx_handler,
  4624. void *rx_handler_data)
  4625. {
  4626. if (netdev_is_rx_handler_busy(dev))
  4627. return -EBUSY;
  4628. if (dev->priv_flags & IFF_NO_RX_HANDLER)
  4629. return -EINVAL;
  4630. /* Note: rx_handler_data must be set before rx_handler */
  4631. rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
  4632. rcu_assign_pointer(dev->rx_handler, rx_handler);
  4633. return 0;
  4634. }
  4635. EXPORT_SYMBOL_GPL(netdev_rx_handler_register);
  4636. /**
  4637. * netdev_rx_handler_unregister - unregister receive handler
  4638. * @dev: device to unregister a handler from
  4639. *
  4640. * Unregister a receive handler from a device.
  4641. *
  4642. * The caller must hold the rtnl_mutex.
  4643. */
  4644. void netdev_rx_handler_unregister(struct net_device *dev)
  4645. {
  4646. ASSERT_RTNL();
  4647. RCU_INIT_POINTER(dev->rx_handler, NULL);
  4648. /* a reader seeing a non NULL rx_handler in a rcu_read_lock()
  4649. * section has a guarantee to see a non NULL rx_handler_data
  4650. * as well.
  4651. */
  4652. synchronize_net();
  4653. RCU_INIT_POINTER(dev->rx_handler_data, NULL);
  4654. }
  4655. EXPORT_SYMBOL_GPL(netdev_rx_handler_unregister);
  4656. /*
  4657. * Limit the use of PFMEMALLOC reserves to those protocols that implement
  4658. * the special handling of PFMEMALLOC skbs.
  4659. */
  4660. static bool skb_pfmemalloc_protocol(struct sk_buff *skb)
  4661. {
  4662. switch (skb->protocol) {
  4663. case htons(ETH_P_ARP):
  4664. case htons(ETH_P_IP):
  4665. case htons(ETH_P_IPV6):
  4666. case htons(ETH_P_8021Q):
  4667. case htons(ETH_P_8021AD):
  4668. return true;
  4669. default:
  4670. return false;
  4671. }
  4672. }
  4673. static inline int nf_ingress(struct sk_buff *skb, struct packet_type **pt_prev,
  4674. int *ret, struct net_device *orig_dev)
  4675. {
  4676. if (nf_hook_ingress_active(skb)) {
  4677. int ingress_retval;
  4678. if (*pt_prev) {
  4679. *ret = deliver_skb(skb, *pt_prev, orig_dev);
  4680. *pt_prev = NULL;
  4681. }
  4682. rcu_read_lock();
  4683. ingress_retval = nf_hook_ingress(skb);
  4684. rcu_read_unlock();
  4685. return ingress_retval;
  4686. }
  4687. return 0;
  4688. }
  4689. static int __netif_receive_skb_core(struct sk_buff **pskb, bool pfmemalloc,
  4690. struct packet_type **ppt_prev)
  4691. {
  4692. struct packet_type *ptype, *pt_prev;
  4693. rx_handler_func_t *rx_handler;
  4694. struct sk_buff *skb = *pskb;
  4695. struct net_device *orig_dev;
  4696. bool deliver_exact = false;
  4697. int ret = NET_RX_DROP;
  4698. __be16 type;
  4699. net_timestamp_check(!READ_ONCE(net_hotdata.tstamp_prequeue), skb);
  4700. trace_netif_receive_skb(skb);
  4701. orig_dev = skb->dev;
  4702. skb_reset_network_header(skb);
  4703. if (!skb_transport_header_was_set(skb))
  4704. skb_reset_transport_header(skb);
  4705. skb_reset_mac_len(skb);
  4706. pt_prev = NULL;
  4707. another_round:
  4708. skb->skb_iif = skb->dev->ifindex;
  4709. __this_cpu_inc(softnet_data.processed);
  4710. if (static_branch_unlikely(&generic_xdp_needed_key)) {
  4711. int ret2;
  4712. migrate_disable();
  4713. ret2 = do_xdp_generic(rcu_dereference(skb->dev->xdp_prog),
  4714. &skb);
  4715. migrate_enable();
  4716. if (ret2 != XDP_PASS) {
  4717. ret = NET_RX_DROP;
  4718. goto out;
  4719. }
  4720. }
  4721. if (eth_type_vlan(skb->protocol)) {
  4722. skb = skb_vlan_untag(skb);
  4723. if (unlikely(!skb))
  4724. goto out;
  4725. }
  4726. if (skb_skip_tc_classify(skb))
  4727. goto skip_classify;
  4728. if (pfmemalloc)
  4729. goto skip_taps;
  4730. list_for_each_entry_rcu(ptype, &net_hotdata.ptype_all, list) {
  4731. if (pt_prev)
  4732. ret = deliver_skb(skb, pt_prev, orig_dev);
  4733. pt_prev = ptype;
  4734. }
  4735. list_for_each_entry_rcu(ptype, &skb->dev->ptype_all, list) {
  4736. if (pt_prev)
  4737. ret = deliver_skb(skb, pt_prev, orig_dev);
  4738. pt_prev = ptype;
  4739. }
  4740. skip_taps:
  4741. #ifdef CONFIG_NET_INGRESS
  4742. if (static_branch_unlikely(&ingress_needed_key)) {
  4743. bool another = false;
  4744. nf_skip_egress(skb, true);
  4745. skb = sch_handle_ingress(skb, &pt_prev, &ret, orig_dev,
  4746. &another);
  4747. if (another)
  4748. goto another_round;
  4749. if (!skb)
  4750. goto out;
  4751. nf_skip_egress(skb, false);
  4752. if (nf_ingress(skb, &pt_prev, &ret, orig_dev) < 0)
  4753. goto out;
  4754. }
  4755. #endif
  4756. skb_reset_redirect(skb);
  4757. skip_classify:
  4758. if (pfmemalloc && !skb_pfmemalloc_protocol(skb))
  4759. goto drop;
  4760. if (skb_vlan_tag_present(skb)) {
  4761. if (pt_prev) {
  4762. ret = deliver_skb(skb, pt_prev, orig_dev);
  4763. pt_prev = NULL;
  4764. }
  4765. if (vlan_do_receive(&skb))
  4766. goto another_round;
  4767. else if (unlikely(!skb))
  4768. goto out;
  4769. }
  4770. rx_handler = rcu_dereference(skb->dev->rx_handler);
  4771. if (rx_handler) {
  4772. if (pt_prev) {
  4773. ret = deliver_skb(skb, pt_prev, orig_dev);
  4774. pt_prev = NULL;
  4775. }
  4776. switch (rx_handler(&skb)) {
  4777. case RX_HANDLER_CONSUMED:
  4778. ret = NET_RX_SUCCESS;
  4779. goto out;
  4780. case RX_HANDLER_ANOTHER:
  4781. goto another_round;
  4782. case RX_HANDLER_EXACT:
  4783. deliver_exact = true;
  4784. break;
  4785. case RX_HANDLER_PASS:
  4786. break;
  4787. default:
  4788. BUG();
  4789. }
  4790. }
  4791. if (unlikely(skb_vlan_tag_present(skb)) && !netdev_uses_dsa(skb->dev)) {
  4792. check_vlan_id:
  4793. if (skb_vlan_tag_get_id(skb)) {
  4794. /* Vlan id is non 0 and vlan_do_receive() above couldn't
  4795. * find vlan device.
  4796. */
  4797. skb->pkt_type = PACKET_OTHERHOST;
  4798. } else if (eth_type_vlan(skb->protocol)) {
  4799. /* Outer header is 802.1P with vlan 0, inner header is
  4800. * 802.1Q or 802.1AD and vlan_do_receive() above could
  4801. * not find vlan dev for vlan id 0.
  4802. */
  4803. __vlan_hwaccel_clear_tag(skb);
  4804. skb = skb_vlan_untag(skb);
  4805. if (unlikely(!skb))
  4806. goto out;
  4807. if (vlan_do_receive(&skb))
  4808. /* After stripping off 802.1P header with vlan 0
  4809. * vlan dev is found for inner header.
  4810. */
  4811. goto another_round;
  4812. else if (unlikely(!skb))
  4813. goto out;
  4814. else
  4815. /* We have stripped outer 802.1P vlan 0 header.
  4816. * But could not find vlan dev.
  4817. * check again for vlan id to set OTHERHOST.
  4818. */
  4819. goto check_vlan_id;
  4820. }
  4821. /* Note: we might in the future use prio bits
  4822. * and set skb->priority like in vlan_do_receive()
  4823. * For the time being, just ignore Priority Code Point
  4824. */
  4825. __vlan_hwaccel_clear_tag(skb);
  4826. }
  4827. type = skb->protocol;
  4828. /* deliver only exact match when indicated */
  4829. if (likely(!deliver_exact)) {
  4830. deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
  4831. &ptype_base[ntohs(type) &
  4832. PTYPE_HASH_MASK]);
  4833. }
  4834. deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
  4835. &orig_dev->ptype_specific);
  4836. if (unlikely(skb->dev != orig_dev)) {
  4837. deliver_ptype_list_skb(skb, &pt_prev, orig_dev, type,
  4838. &skb->dev->ptype_specific);
  4839. }
  4840. if (pt_prev) {
  4841. if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC)))
  4842. goto drop;
  4843. *ppt_prev = pt_prev;
  4844. } else {
  4845. drop:
  4846. if (!deliver_exact)
  4847. dev_core_stats_rx_dropped_inc(skb->dev);
  4848. else
  4849. dev_core_stats_rx_nohandler_inc(skb->dev);
  4850. kfree_skb_reason(skb, SKB_DROP_REASON_UNHANDLED_PROTO);
  4851. /* Jamal, now you will not able to escape explaining
  4852. * me how you were going to use this. :-)
  4853. */
  4854. ret = NET_RX_DROP;
  4855. }
  4856. out:
  4857. /* The invariant here is that if *ppt_prev is not NULL
  4858. * then skb should also be non-NULL.
  4859. *
  4860. * Apparently *ppt_prev assignment above holds this invariant due to
  4861. * skb dereferencing near it.
  4862. */
  4863. *pskb = skb;
  4864. return ret;
  4865. }
  4866. static int __netif_receive_skb_one_core(struct sk_buff *skb, bool pfmemalloc)
  4867. {
  4868. struct net_device *orig_dev = skb->dev;
  4869. struct packet_type *pt_prev = NULL;
  4870. int ret;
  4871. ret = __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
  4872. if (pt_prev)
  4873. ret = INDIRECT_CALL_INET(pt_prev->func, ipv6_rcv, ip_rcv, skb,
  4874. skb->dev, pt_prev, orig_dev);
  4875. return ret;
  4876. }
  4877. /**
  4878. * netif_receive_skb_core - special purpose version of netif_receive_skb
  4879. * @skb: buffer to process
  4880. *
  4881. * More direct receive version of netif_receive_skb(). It should
  4882. * only be used by callers that have a need to skip RPS and Generic XDP.
  4883. * Caller must also take care of handling if ``(page_is_)pfmemalloc``.
  4884. *
  4885. * This function may only be called from softirq context and interrupts
  4886. * should be enabled.
  4887. *
  4888. * Return values (usually ignored):
  4889. * NET_RX_SUCCESS: no congestion
  4890. * NET_RX_DROP: packet was dropped
  4891. */
  4892. int netif_receive_skb_core(struct sk_buff *skb)
  4893. {
  4894. int ret;
  4895. rcu_read_lock();
  4896. ret = __netif_receive_skb_one_core(skb, false);
  4897. rcu_read_unlock();
  4898. return ret;
  4899. }
  4900. EXPORT_SYMBOL(netif_receive_skb_core);
  4901. static inline void __netif_receive_skb_list_ptype(struct list_head *head,
  4902. struct packet_type *pt_prev,
  4903. struct net_device *orig_dev)
  4904. {
  4905. struct sk_buff *skb, *next;
  4906. if (!pt_prev)
  4907. return;
  4908. if (list_empty(head))
  4909. return;
  4910. if (pt_prev->list_func != NULL)
  4911. INDIRECT_CALL_INET(pt_prev->list_func, ipv6_list_rcv,
  4912. ip_list_rcv, head, pt_prev, orig_dev);
  4913. else
  4914. list_for_each_entry_safe(skb, next, head, list) {
  4915. skb_list_del_init(skb);
  4916. pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
  4917. }
  4918. }
  4919. static void __netif_receive_skb_list_core(struct list_head *head, bool pfmemalloc)
  4920. {
  4921. /* Fast-path assumptions:
  4922. * - There is no RX handler.
  4923. * - Only one packet_type matches.
  4924. * If either of these fails, we will end up doing some per-packet
  4925. * processing in-line, then handling the 'last ptype' for the whole
  4926. * sublist. This can't cause out-of-order delivery to any single ptype,
  4927. * because the 'last ptype' must be constant across the sublist, and all
  4928. * other ptypes are handled per-packet.
  4929. */
  4930. /* Current (common) ptype of sublist */
  4931. struct packet_type *pt_curr = NULL;
  4932. /* Current (common) orig_dev of sublist */
  4933. struct net_device *od_curr = NULL;
  4934. struct sk_buff *skb, *next;
  4935. LIST_HEAD(sublist);
  4936. list_for_each_entry_safe(skb, next, head, list) {
  4937. struct net_device *orig_dev = skb->dev;
  4938. struct packet_type *pt_prev = NULL;
  4939. skb_list_del_init(skb);
  4940. __netif_receive_skb_core(&skb, pfmemalloc, &pt_prev);
  4941. if (!pt_prev)
  4942. continue;
  4943. if (pt_curr != pt_prev || od_curr != orig_dev) {
  4944. /* dispatch old sublist */
  4945. __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
  4946. /* start new sublist */
  4947. INIT_LIST_HEAD(&sublist);
  4948. pt_curr = pt_prev;
  4949. od_curr = orig_dev;
  4950. }
  4951. list_add_tail(&skb->list, &sublist);
  4952. }
  4953. /* dispatch final sublist */
  4954. __netif_receive_skb_list_ptype(&sublist, pt_curr, od_curr);
  4955. }
  4956. static int __netif_receive_skb(struct sk_buff *skb)
  4957. {
  4958. int ret;
  4959. if (sk_memalloc_socks() && skb_pfmemalloc(skb)) {
  4960. unsigned int noreclaim_flag;
  4961. /*
  4962. * PFMEMALLOC skbs are special, they should
  4963. * - be delivered to SOCK_MEMALLOC sockets only
  4964. * - stay away from userspace
  4965. * - have bounded memory usage
  4966. *
  4967. * Use PF_MEMALLOC as this saves us from propagating the allocation
  4968. * context down to all allocation sites.
  4969. */
  4970. noreclaim_flag = memalloc_noreclaim_save();
  4971. ret = __netif_receive_skb_one_core(skb, true);
  4972. memalloc_noreclaim_restore(noreclaim_flag);
  4973. } else
  4974. ret = __netif_receive_skb_one_core(skb, false);
  4975. return ret;
  4976. }
  4977. static void __netif_receive_skb_list(struct list_head *head)
  4978. {
  4979. unsigned long noreclaim_flag = 0;
  4980. struct sk_buff *skb, *next;
  4981. bool pfmemalloc = false; /* Is current sublist PF_MEMALLOC? */
  4982. list_for_each_entry_safe(skb, next, head, list) {
  4983. if ((sk_memalloc_socks() && skb_pfmemalloc(skb)) != pfmemalloc) {
  4984. struct list_head sublist;
  4985. /* Handle the previous sublist */
  4986. list_cut_before(&sublist, head, &skb->list);
  4987. if (!list_empty(&sublist))
  4988. __netif_receive_skb_list_core(&sublist, pfmemalloc);
  4989. pfmemalloc = !pfmemalloc;
  4990. /* See comments in __netif_receive_skb */
  4991. if (pfmemalloc)
  4992. noreclaim_flag = memalloc_noreclaim_save();
  4993. else
  4994. memalloc_noreclaim_restore(noreclaim_flag);
  4995. }
  4996. }
  4997. /* Handle the remaining sublist */
  4998. if (!list_empty(head))
  4999. __netif_receive_skb_list_core(head, pfmemalloc);
  5000. /* Restore pflags */
  5001. if (pfmemalloc)
  5002. memalloc_noreclaim_restore(noreclaim_flag);
  5003. }
  5004. static int generic_xdp_install(struct net_device *dev, struct netdev_bpf *xdp)
  5005. {
  5006. struct bpf_prog *old = rtnl_dereference(dev->xdp_prog);
  5007. struct bpf_prog *new = xdp->prog;
  5008. int ret = 0;
  5009. switch (xdp->command) {
  5010. case XDP_SETUP_PROG:
  5011. rcu_assign_pointer(dev->xdp_prog, new);
  5012. if (old)
  5013. bpf_prog_put(old);
  5014. if (old && !new) {
  5015. static_branch_dec(&generic_xdp_needed_key);
  5016. } else if (new && !old) {
  5017. static_branch_inc(&generic_xdp_needed_key);
  5018. dev_disable_lro(dev);
  5019. dev_disable_gro_hw(dev);
  5020. }
  5021. break;
  5022. default:
  5023. ret = -EINVAL;
  5024. break;
  5025. }
  5026. return ret;
  5027. }
  5028. static int netif_receive_skb_internal(struct sk_buff *skb)
  5029. {
  5030. int ret;
  5031. net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue), skb);
  5032. if (skb_defer_rx_timestamp(skb))
  5033. return NET_RX_SUCCESS;
  5034. rcu_read_lock();
  5035. #ifdef CONFIG_RPS
  5036. if (static_branch_unlikely(&rps_needed)) {
  5037. struct rps_dev_flow voidflow, *rflow = &voidflow;
  5038. int cpu = get_rps_cpu(skb->dev, skb, &rflow);
  5039. if (cpu >= 0) {
  5040. ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
  5041. rcu_read_unlock();
  5042. return ret;
  5043. }
  5044. }
  5045. #endif
  5046. ret = __netif_receive_skb(skb);
  5047. rcu_read_unlock();
  5048. return ret;
  5049. }
  5050. void netif_receive_skb_list_internal(struct list_head *head)
  5051. {
  5052. struct sk_buff *skb, *next;
  5053. LIST_HEAD(sublist);
  5054. list_for_each_entry_safe(skb, next, head, list) {
  5055. net_timestamp_check(READ_ONCE(net_hotdata.tstamp_prequeue),
  5056. skb);
  5057. skb_list_del_init(skb);
  5058. if (!skb_defer_rx_timestamp(skb))
  5059. list_add_tail(&skb->list, &sublist);
  5060. }
  5061. list_splice_init(&sublist, head);
  5062. rcu_read_lock();
  5063. #ifdef CONFIG_RPS
  5064. if (static_branch_unlikely(&rps_needed)) {
  5065. list_for_each_entry_safe(skb, next, head, list) {
  5066. struct rps_dev_flow voidflow, *rflow = &voidflow;
  5067. int cpu = get_rps_cpu(skb->dev, skb, &rflow);
  5068. if (cpu >= 0) {
  5069. /* Will be handled, remove from list */
  5070. skb_list_del_init(skb);
  5071. enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
  5072. }
  5073. }
  5074. }
  5075. #endif
  5076. __netif_receive_skb_list(head);
  5077. rcu_read_unlock();
  5078. }
  5079. /**
  5080. * netif_receive_skb - process receive buffer from network
  5081. * @skb: buffer to process
  5082. *
  5083. * netif_receive_skb() is the main receive data processing function.
  5084. * It always succeeds. The buffer may be dropped during processing
  5085. * for congestion control or by the protocol layers.
  5086. *
  5087. * This function may only be called from softirq context and interrupts
  5088. * should be enabled.
  5089. *
  5090. * Return values (usually ignored):
  5091. * NET_RX_SUCCESS: no congestion
  5092. * NET_RX_DROP: packet was dropped
  5093. */
  5094. int netif_receive_skb(struct sk_buff *skb)
  5095. {
  5096. int ret;
  5097. trace_netif_receive_skb_entry(skb);
  5098. ret = netif_receive_skb_internal(skb);
  5099. trace_netif_receive_skb_exit(ret);
  5100. return ret;
  5101. }
  5102. EXPORT_SYMBOL(netif_receive_skb);
  5103. /**
  5104. * netif_receive_skb_list - process many receive buffers from network
  5105. * @head: list of skbs to process.
  5106. *
  5107. * Since return value of netif_receive_skb() is normally ignored, and
  5108. * wouldn't be meaningful for a list, this function returns void.
  5109. *
  5110. * This function may only be called from softirq context and interrupts
  5111. * should be enabled.
  5112. */
  5113. void netif_receive_skb_list(struct list_head *head)
  5114. {
  5115. struct sk_buff *skb;
  5116. if (list_empty(head))
  5117. return;
  5118. if (trace_netif_receive_skb_list_entry_enabled()) {
  5119. list_for_each_entry(skb, head, list)
  5120. trace_netif_receive_skb_list_entry(skb);
  5121. }
  5122. netif_receive_skb_list_internal(head);
  5123. trace_netif_receive_skb_list_exit(0);
  5124. }
  5125. EXPORT_SYMBOL(netif_receive_skb_list);
  5126. static DEFINE_PER_CPU(struct work_struct, flush_works);
  5127. /* Network device is going away, flush any packets still pending */
  5128. static void flush_backlog(struct work_struct *work)
  5129. {
  5130. struct sk_buff *skb, *tmp;
  5131. struct sk_buff_head list;
  5132. struct softnet_data *sd;
  5133. __skb_queue_head_init(&list);
  5134. local_bh_disable();
  5135. sd = this_cpu_ptr(&softnet_data);
  5136. backlog_lock_irq_disable(sd);
  5137. skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
  5138. if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) {
  5139. __skb_unlink(skb, &sd->input_pkt_queue);
  5140. __skb_queue_tail(&list, skb);
  5141. rps_input_queue_head_incr(sd);
  5142. }
  5143. }
  5144. backlog_unlock_irq_enable(sd);
  5145. local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
  5146. skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
  5147. if (READ_ONCE(skb->dev->reg_state) == NETREG_UNREGISTERING) {
  5148. __skb_unlink(skb, &sd->process_queue);
  5149. __skb_queue_tail(&list, skb);
  5150. rps_input_queue_head_incr(sd);
  5151. }
  5152. }
  5153. local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
  5154. local_bh_enable();
  5155. __skb_queue_purge_reason(&list, SKB_DROP_REASON_DEV_READY);
  5156. }
  5157. static bool flush_required(int cpu)
  5158. {
  5159. #if IS_ENABLED(CONFIG_RPS)
  5160. struct softnet_data *sd = &per_cpu(softnet_data, cpu);
  5161. bool do_flush;
  5162. backlog_lock_irq_disable(sd);
  5163. /* as insertion into process_queue happens with the rps lock held,
  5164. * process_queue access may race only with dequeue
  5165. */
  5166. do_flush = !skb_queue_empty(&sd->input_pkt_queue) ||
  5167. !skb_queue_empty_lockless(&sd->process_queue);
  5168. backlog_unlock_irq_enable(sd);
  5169. return do_flush;
  5170. #endif
  5171. /* without RPS we can't safely check input_pkt_queue: during a
  5172. * concurrent remote skb_queue_splice() we can detect as empty both
  5173. * input_pkt_queue and process_queue even if the latter could end-up
  5174. * containing a lot of packets.
  5175. */
  5176. return true;
  5177. }
  5178. static void flush_all_backlogs(void)
  5179. {
  5180. static cpumask_t flush_cpus;
  5181. unsigned int cpu;
  5182. /* since we are under rtnl lock protection we can use static data
  5183. * for the cpumask and avoid allocating on stack the possibly
  5184. * large mask
  5185. */
  5186. ASSERT_RTNL();
  5187. cpus_read_lock();
  5188. cpumask_clear(&flush_cpus);
  5189. for_each_online_cpu(cpu) {
  5190. if (flush_required(cpu)) {
  5191. queue_work_on(cpu, system_highpri_wq,
  5192. per_cpu_ptr(&flush_works, cpu));
  5193. cpumask_set_cpu(cpu, &flush_cpus);
  5194. }
  5195. }
  5196. /* we can have in flight packet[s] on the cpus we are not flushing,
  5197. * synchronize_net() in unregister_netdevice_many() will take care of
  5198. * them
  5199. */
  5200. for_each_cpu(cpu, &flush_cpus)
  5201. flush_work(per_cpu_ptr(&flush_works, cpu));
  5202. cpus_read_unlock();
  5203. }
  5204. static void net_rps_send_ipi(struct softnet_data *remsd)
  5205. {
  5206. #ifdef CONFIG_RPS
  5207. while (remsd) {
  5208. struct softnet_data *next = remsd->rps_ipi_next;
  5209. if (cpu_online(remsd->cpu))
  5210. smp_call_function_single_async(remsd->cpu, &remsd->csd);
  5211. remsd = next;
  5212. }
  5213. #endif
  5214. }
  5215. /*
  5216. * net_rps_action_and_irq_enable sends any pending IPI's for rps.
  5217. * Note: called with local irq disabled, but exits with local irq enabled.
  5218. */
  5219. static void net_rps_action_and_irq_enable(struct softnet_data *sd)
  5220. {
  5221. #ifdef CONFIG_RPS
  5222. struct softnet_data *remsd = sd->rps_ipi_list;
  5223. if (!use_backlog_threads() && remsd) {
  5224. sd->rps_ipi_list = NULL;
  5225. local_irq_enable();
  5226. /* Send pending IPI's to kick RPS processing on remote cpus. */
  5227. net_rps_send_ipi(remsd);
  5228. } else
  5229. #endif
  5230. local_irq_enable();
  5231. }
  5232. static bool sd_has_rps_ipi_waiting(struct softnet_data *sd)
  5233. {
  5234. #ifdef CONFIG_RPS
  5235. return !use_backlog_threads() && sd->rps_ipi_list;
  5236. #else
  5237. return false;
  5238. #endif
  5239. }
  5240. static int process_backlog(struct napi_struct *napi, int quota)
  5241. {
  5242. struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
  5243. bool again = true;
  5244. int work = 0;
  5245. /* Check if we have pending ipi, its better to send them now,
  5246. * not waiting net_rx_action() end.
  5247. */
  5248. if (sd_has_rps_ipi_waiting(sd)) {
  5249. local_irq_disable();
  5250. net_rps_action_and_irq_enable(sd);
  5251. }
  5252. napi->weight = READ_ONCE(net_hotdata.dev_rx_weight);
  5253. while (again) {
  5254. struct sk_buff *skb;
  5255. local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
  5256. while ((skb = __skb_dequeue(&sd->process_queue))) {
  5257. local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
  5258. rcu_read_lock();
  5259. __netif_receive_skb(skb);
  5260. rcu_read_unlock();
  5261. if (++work >= quota) {
  5262. rps_input_queue_head_add(sd, work);
  5263. return work;
  5264. }
  5265. local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
  5266. }
  5267. local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
  5268. backlog_lock_irq_disable(sd);
  5269. if (skb_queue_empty(&sd->input_pkt_queue)) {
  5270. /*
  5271. * Inline a custom version of __napi_complete().
  5272. * only current cpu owns and manipulates this napi,
  5273. * and NAPI_STATE_SCHED is the only possible flag set
  5274. * on backlog.
  5275. * We can use a plain write instead of clear_bit(),
  5276. * and we dont need an smp_mb() memory barrier.
  5277. */
  5278. napi->state &= NAPIF_STATE_THREADED;
  5279. again = false;
  5280. } else {
  5281. local_lock_nested_bh(&softnet_data.process_queue_bh_lock);
  5282. skb_queue_splice_tail_init(&sd->input_pkt_queue,
  5283. &sd->process_queue);
  5284. local_unlock_nested_bh(&softnet_data.process_queue_bh_lock);
  5285. }
  5286. backlog_unlock_irq_enable(sd);
  5287. }
  5288. if (work)
  5289. rps_input_queue_head_add(sd, work);
  5290. return work;
  5291. }
  5292. /**
  5293. * __napi_schedule - schedule for receive
  5294. * @n: entry to schedule
  5295. *
  5296. * The entry's receive function will be scheduled to run.
  5297. * Consider using __napi_schedule_irqoff() if hard irqs are masked.
  5298. */
  5299. void __napi_schedule(struct napi_struct *n)
  5300. {
  5301. unsigned long flags;
  5302. local_irq_save(flags);
  5303. ____napi_schedule(this_cpu_ptr(&softnet_data), n);
  5304. local_irq_restore(flags);
  5305. }
  5306. EXPORT_SYMBOL(__napi_schedule);
  5307. /**
  5308. * napi_schedule_prep - check if napi can be scheduled
  5309. * @n: napi context
  5310. *
  5311. * Test if NAPI routine is already running, and if not mark
  5312. * it as running. This is used as a condition variable to
  5313. * insure only one NAPI poll instance runs. We also make
  5314. * sure there is no pending NAPI disable.
  5315. */
  5316. bool napi_schedule_prep(struct napi_struct *n)
  5317. {
  5318. unsigned long new, val = READ_ONCE(n->state);
  5319. do {
  5320. if (unlikely(val & NAPIF_STATE_DISABLE))
  5321. return false;
  5322. new = val | NAPIF_STATE_SCHED;
  5323. /* Sets STATE_MISSED bit if STATE_SCHED was already set
  5324. * This was suggested by Alexander Duyck, as compiler
  5325. * emits better code than :
  5326. * if (val & NAPIF_STATE_SCHED)
  5327. * new |= NAPIF_STATE_MISSED;
  5328. */
  5329. new |= (val & NAPIF_STATE_SCHED) / NAPIF_STATE_SCHED *
  5330. NAPIF_STATE_MISSED;
  5331. } while (!try_cmpxchg(&n->state, &val, new));
  5332. return !(val & NAPIF_STATE_SCHED);
  5333. }
  5334. EXPORT_SYMBOL(napi_schedule_prep);
  5335. /**
  5336. * __napi_schedule_irqoff - schedule for receive
  5337. * @n: entry to schedule
  5338. *
  5339. * Variant of __napi_schedule() assuming hard irqs are masked.
  5340. *
  5341. * On PREEMPT_RT enabled kernels this maps to __napi_schedule()
  5342. * because the interrupt disabled assumption might not be true
  5343. * due to force-threaded interrupts and spinlock substitution.
  5344. */
  5345. void __napi_schedule_irqoff(struct napi_struct *n)
  5346. {
  5347. if (!IS_ENABLED(CONFIG_PREEMPT_RT))
  5348. ____napi_schedule(this_cpu_ptr(&softnet_data), n);
  5349. else
  5350. __napi_schedule(n);
  5351. }
  5352. EXPORT_SYMBOL(__napi_schedule_irqoff);
  5353. bool napi_complete_done(struct napi_struct *n, int work_done)
  5354. {
  5355. unsigned long flags, val, new, timeout = 0;
  5356. bool ret = true;
  5357. /*
  5358. * 1) Don't let napi dequeue from the cpu poll list
  5359. * just in case its running on a different cpu.
  5360. * 2) If we are busy polling, do nothing here, we have
  5361. * the guarantee we will be called later.
  5362. */
  5363. if (unlikely(n->state & (NAPIF_STATE_NPSVC |
  5364. NAPIF_STATE_IN_BUSY_POLL)))
  5365. return false;
  5366. if (work_done) {
  5367. if (n->gro_bitmask)
  5368. timeout = READ_ONCE(n->dev->gro_flush_timeout);
  5369. n->defer_hard_irqs_count = READ_ONCE(n->dev->napi_defer_hard_irqs);
  5370. }
  5371. if (n->defer_hard_irqs_count > 0) {
  5372. n->defer_hard_irqs_count--;
  5373. timeout = READ_ONCE(n->dev->gro_flush_timeout);
  5374. if (timeout)
  5375. ret = false;
  5376. }
  5377. if (n->gro_bitmask) {
  5378. /* When the NAPI instance uses a timeout and keeps postponing
  5379. * it, we need to bound somehow the time packets are kept in
  5380. * the GRO layer
  5381. */
  5382. napi_gro_flush(n, !!timeout);
  5383. }
  5384. gro_normal_list(n);
  5385. if (unlikely(!list_empty(&n->poll_list))) {
  5386. /* If n->poll_list is not empty, we need to mask irqs */
  5387. local_irq_save(flags);
  5388. list_del_init(&n->poll_list);
  5389. local_irq_restore(flags);
  5390. }
  5391. WRITE_ONCE(n->list_owner, -1);
  5392. val = READ_ONCE(n->state);
  5393. do {
  5394. WARN_ON_ONCE(!(val & NAPIF_STATE_SCHED));
  5395. new = val & ~(NAPIF_STATE_MISSED | NAPIF_STATE_SCHED |
  5396. NAPIF_STATE_SCHED_THREADED |
  5397. NAPIF_STATE_PREFER_BUSY_POLL);
  5398. /* If STATE_MISSED was set, leave STATE_SCHED set,
  5399. * because we will call napi->poll() one more time.
  5400. * This C code was suggested by Alexander Duyck to help gcc.
  5401. */
  5402. new |= (val & NAPIF_STATE_MISSED) / NAPIF_STATE_MISSED *
  5403. NAPIF_STATE_SCHED;
  5404. } while (!try_cmpxchg(&n->state, &val, new));
  5405. if (unlikely(val & NAPIF_STATE_MISSED)) {
  5406. __napi_schedule(n);
  5407. return false;
  5408. }
  5409. if (timeout)
  5410. hrtimer_start(&n->timer, ns_to_ktime(timeout),
  5411. HRTIMER_MODE_REL_PINNED);
  5412. return ret;
  5413. }
  5414. EXPORT_SYMBOL(napi_complete_done);
  5415. static void skb_defer_free_flush(struct softnet_data *sd)
  5416. {
  5417. struct sk_buff *skb, *next;
  5418. /* Paired with WRITE_ONCE() in skb_attempt_defer_free() */
  5419. if (!READ_ONCE(sd->defer_list))
  5420. return;
  5421. spin_lock(&sd->defer_lock);
  5422. skb = sd->defer_list;
  5423. sd->defer_list = NULL;
  5424. sd->defer_count = 0;
  5425. spin_unlock(&sd->defer_lock);
  5426. while (skb != NULL) {
  5427. next = skb->next;
  5428. napi_consume_skb(skb, 1);
  5429. skb = next;
  5430. }
  5431. }
  5432. #if defined(CONFIG_NET_RX_BUSY_POLL)
  5433. static void __busy_poll_stop(struct napi_struct *napi, bool skip_schedule)
  5434. {
  5435. if (!skip_schedule) {
  5436. gro_normal_list(napi);
  5437. __napi_schedule(napi);
  5438. return;
  5439. }
  5440. if (napi->gro_bitmask) {
  5441. /* flush too old packets
  5442. * If HZ < 1000, flush all packets.
  5443. */
  5444. napi_gro_flush(napi, HZ >= 1000);
  5445. }
  5446. gro_normal_list(napi);
  5447. clear_bit(NAPI_STATE_SCHED, &napi->state);
  5448. }
  5449. enum {
  5450. NAPI_F_PREFER_BUSY_POLL = 1,
  5451. NAPI_F_END_ON_RESCHED = 2,
  5452. };
  5453. static void busy_poll_stop(struct napi_struct *napi, void *have_poll_lock,
  5454. unsigned flags, u16 budget)
  5455. {
  5456. struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
  5457. bool skip_schedule = false;
  5458. unsigned long timeout;
  5459. int rc;
  5460. /* Busy polling means there is a high chance device driver hard irq
  5461. * could not grab NAPI_STATE_SCHED, and that NAPI_STATE_MISSED was
  5462. * set in napi_schedule_prep().
  5463. * Since we are about to call napi->poll() once more, we can safely
  5464. * clear NAPI_STATE_MISSED.
  5465. *
  5466. * Note: x86 could use a single "lock and ..." instruction
  5467. * to perform these two clear_bit()
  5468. */
  5469. clear_bit(NAPI_STATE_MISSED, &napi->state);
  5470. clear_bit(NAPI_STATE_IN_BUSY_POLL, &napi->state);
  5471. local_bh_disable();
  5472. bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
  5473. if (flags & NAPI_F_PREFER_BUSY_POLL) {
  5474. napi->defer_hard_irqs_count = READ_ONCE(napi->dev->napi_defer_hard_irqs);
  5475. timeout = READ_ONCE(napi->dev->gro_flush_timeout);
  5476. if (napi->defer_hard_irqs_count && timeout) {
  5477. hrtimer_start(&napi->timer, ns_to_ktime(timeout), HRTIMER_MODE_REL_PINNED);
  5478. skip_schedule = true;
  5479. }
  5480. }
  5481. /* All we really want here is to re-enable device interrupts.
  5482. * Ideally, a new ndo_busy_poll_stop() could avoid another round.
  5483. */
  5484. rc = napi->poll(napi, budget);
  5485. /* We can't gro_normal_list() here, because napi->poll() might have
  5486. * rearmed the napi (napi_complete_done()) in which case it could
  5487. * already be running on another CPU.
  5488. */
  5489. trace_napi_poll(napi, rc, budget);
  5490. netpoll_poll_unlock(have_poll_lock);
  5491. if (rc == budget)
  5492. __busy_poll_stop(napi, skip_schedule);
  5493. bpf_net_ctx_clear(bpf_net_ctx);
  5494. local_bh_enable();
  5495. }
  5496. static void __napi_busy_loop(unsigned int napi_id,
  5497. bool (*loop_end)(void *, unsigned long),
  5498. void *loop_end_arg, unsigned flags, u16 budget)
  5499. {
  5500. unsigned long start_time = loop_end ? busy_loop_current_time() : 0;
  5501. int (*napi_poll)(struct napi_struct *napi, int budget);
  5502. struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
  5503. void *have_poll_lock = NULL;
  5504. struct napi_struct *napi;
  5505. WARN_ON_ONCE(!rcu_read_lock_held());
  5506. restart:
  5507. napi_poll = NULL;
  5508. napi = napi_by_id(napi_id);
  5509. if (!napi)
  5510. return;
  5511. if (!IS_ENABLED(CONFIG_PREEMPT_RT))
  5512. preempt_disable();
  5513. for (;;) {
  5514. int work = 0;
  5515. local_bh_disable();
  5516. bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
  5517. if (!napi_poll) {
  5518. unsigned long val = READ_ONCE(napi->state);
  5519. /* If multiple threads are competing for this napi,
  5520. * we avoid dirtying napi->state as much as we can.
  5521. */
  5522. if (val & (NAPIF_STATE_DISABLE | NAPIF_STATE_SCHED |
  5523. NAPIF_STATE_IN_BUSY_POLL)) {
  5524. if (flags & NAPI_F_PREFER_BUSY_POLL)
  5525. set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
  5526. goto count;
  5527. }
  5528. if (cmpxchg(&napi->state, val,
  5529. val | NAPIF_STATE_IN_BUSY_POLL |
  5530. NAPIF_STATE_SCHED) != val) {
  5531. if (flags & NAPI_F_PREFER_BUSY_POLL)
  5532. set_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
  5533. goto count;
  5534. }
  5535. have_poll_lock = netpoll_poll_lock(napi);
  5536. napi_poll = napi->poll;
  5537. }
  5538. work = napi_poll(napi, budget);
  5539. trace_napi_poll(napi, work, budget);
  5540. gro_normal_list(napi);
  5541. count:
  5542. if (work > 0)
  5543. __NET_ADD_STATS(dev_net(napi->dev),
  5544. LINUX_MIB_BUSYPOLLRXPACKETS, work);
  5545. skb_defer_free_flush(this_cpu_ptr(&softnet_data));
  5546. bpf_net_ctx_clear(bpf_net_ctx);
  5547. local_bh_enable();
  5548. if (!loop_end || loop_end(loop_end_arg, start_time))
  5549. break;
  5550. if (unlikely(need_resched())) {
  5551. if (flags & NAPI_F_END_ON_RESCHED)
  5552. break;
  5553. if (napi_poll)
  5554. busy_poll_stop(napi, have_poll_lock, flags, budget);
  5555. if (!IS_ENABLED(CONFIG_PREEMPT_RT))
  5556. preempt_enable();
  5557. rcu_read_unlock();
  5558. cond_resched();
  5559. rcu_read_lock();
  5560. if (loop_end(loop_end_arg, start_time))
  5561. return;
  5562. goto restart;
  5563. }
  5564. cpu_relax();
  5565. }
  5566. if (napi_poll)
  5567. busy_poll_stop(napi, have_poll_lock, flags, budget);
  5568. if (!IS_ENABLED(CONFIG_PREEMPT_RT))
  5569. preempt_enable();
  5570. }
  5571. void napi_busy_loop_rcu(unsigned int napi_id,
  5572. bool (*loop_end)(void *, unsigned long),
  5573. void *loop_end_arg, bool prefer_busy_poll, u16 budget)
  5574. {
  5575. unsigned flags = NAPI_F_END_ON_RESCHED;
  5576. if (prefer_busy_poll)
  5577. flags |= NAPI_F_PREFER_BUSY_POLL;
  5578. __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
  5579. }
  5580. void napi_busy_loop(unsigned int napi_id,
  5581. bool (*loop_end)(void *, unsigned long),
  5582. void *loop_end_arg, bool prefer_busy_poll, u16 budget)
  5583. {
  5584. unsigned flags = prefer_busy_poll ? NAPI_F_PREFER_BUSY_POLL : 0;
  5585. rcu_read_lock();
  5586. __napi_busy_loop(napi_id, loop_end, loop_end_arg, flags, budget);
  5587. rcu_read_unlock();
  5588. }
  5589. EXPORT_SYMBOL(napi_busy_loop);
  5590. #endif /* CONFIG_NET_RX_BUSY_POLL */
  5591. static void napi_hash_add(struct napi_struct *napi)
  5592. {
  5593. if (test_bit(NAPI_STATE_NO_BUSY_POLL, &napi->state))
  5594. return;
  5595. spin_lock(&napi_hash_lock);
  5596. /* 0..NR_CPUS range is reserved for sender_cpu use */
  5597. do {
  5598. if (unlikely(++napi_gen_id < MIN_NAPI_ID))
  5599. napi_gen_id = MIN_NAPI_ID;
  5600. } while (napi_by_id(napi_gen_id));
  5601. napi->napi_id = napi_gen_id;
  5602. hlist_add_head_rcu(&napi->napi_hash_node,
  5603. &napi_hash[napi->napi_id % HASH_SIZE(napi_hash)]);
  5604. spin_unlock(&napi_hash_lock);
  5605. }
  5606. /* Warning : caller is responsible to make sure rcu grace period
  5607. * is respected before freeing memory containing @napi
  5608. */
  5609. static void napi_hash_del(struct napi_struct *napi)
  5610. {
  5611. spin_lock(&napi_hash_lock);
  5612. hlist_del_init_rcu(&napi->napi_hash_node);
  5613. spin_unlock(&napi_hash_lock);
  5614. }
  5615. static enum hrtimer_restart napi_watchdog(struct hrtimer *timer)
  5616. {
  5617. struct napi_struct *napi;
  5618. napi = container_of(timer, struct napi_struct, timer);
  5619. /* Note : we use a relaxed variant of napi_schedule_prep() not setting
  5620. * NAPI_STATE_MISSED, since we do not react to a device IRQ.
  5621. */
  5622. if (!napi_disable_pending(napi) &&
  5623. !test_and_set_bit(NAPI_STATE_SCHED, &napi->state)) {
  5624. clear_bit(NAPI_STATE_PREFER_BUSY_POLL, &napi->state);
  5625. __napi_schedule_irqoff(napi);
  5626. }
  5627. return HRTIMER_NORESTART;
  5628. }
  5629. static void init_gro_hash(struct napi_struct *napi)
  5630. {
  5631. int i;
  5632. for (i = 0; i < GRO_HASH_BUCKETS; i++) {
  5633. INIT_LIST_HEAD(&napi->gro_hash[i].list);
  5634. napi->gro_hash[i].count = 0;
  5635. }
  5636. napi->gro_bitmask = 0;
  5637. }
  5638. int dev_set_threaded(struct net_device *dev, bool threaded)
  5639. {
  5640. struct napi_struct *napi;
  5641. int err = 0;
  5642. if (dev->threaded == threaded)
  5643. return 0;
  5644. if (threaded) {
  5645. list_for_each_entry(napi, &dev->napi_list, dev_list) {
  5646. if (!napi->thread) {
  5647. err = napi_kthread_create(napi);
  5648. if (err) {
  5649. threaded = false;
  5650. break;
  5651. }
  5652. }
  5653. }
  5654. }
  5655. WRITE_ONCE(dev->threaded, threaded);
  5656. /* Make sure kthread is created before THREADED bit
  5657. * is set.
  5658. */
  5659. smp_mb__before_atomic();
  5660. /* Setting/unsetting threaded mode on a napi might not immediately
  5661. * take effect, if the current napi instance is actively being
  5662. * polled. In this case, the switch between threaded mode and
  5663. * softirq mode will happen in the next round of napi_schedule().
  5664. * This should not cause hiccups/stalls to the live traffic.
  5665. */
  5666. list_for_each_entry(napi, &dev->napi_list, dev_list)
  5667. assign_bit(NAPI_STATE_THREADED, &napi->state, threaded);
  5668. return err;
  5669. }
  5670. EXPORT_SYMBOL(dev_set_threaded);
  5671. /**
  5672. * netif_queue_set_napi - Associate queue with the napi
  5673. * @dev: device to which NAPI and queue belong
  5674. * @queue_index: Index of queue
  5675. * @type: queue type as RX or TX
  5676. * @napi: NAPI context, pass NULL to clear previously set NAPI
  5677. *
  5678. * Set queue with its corresponding napi context. This should be done after
  5679. * registering the NAPI handler for the queue-vector and the queues have been
  5680. * mapped to the corresponding interrupt vector.
  5681. */
  5682. void netif_queue_set_napi(struct net_device *dev, unsigned int queue_index,
  5683. enum netdev_queue_type type, struct napi_struct *napi)
  5684. {
  5685. struct netdev_rx_queue *rxq;
  5686. struct netdev_queue *txq;
  5687. if (WARN_ON_ONCE(napi && !napi->dev))
  5688. return;
  5689. if (dev->reg_state >= NETREG_REGISTERED)
  5690. ASSERT_RTNL();
  5691. switch (type) {
  5692. case NETDEV_QUEUE_TYPE_RX:
  5693. rxq = __netif_get_rx_queue(dev, queue_index);
  5694. rxq->napi = napi;
  5695. return;
  5696. case NETDEV_QUEUE_TYPE_TX:
  5697. txq = netdev_get_tx_queue(dev, queue_index);
  5698. txq->napi = napi;
  5699. return;
  5700. default:
  5701. return;
  5702. }
  5703. }
  5704. EXPORT_SYMBOL(netif_queue_set_napi);
  5705. void netif_napi_add_weight(struct net_device *dev, struct napi_struct *napi,
  5706. int (*poll)(struct napi_struct *, int), int weight)
  5707. {
  5708. if (WARN_ON(test_and_set_bit(NAPI_STATE_LISTED, &napi->state)))
  5709. return;
  5710. INIT_LIST_HEAD(&napi->poll_list);
  5711. INIT_HLIST_NODE(&napi->napi_hash_node);
  5712. hrtimer_init(&napi->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
  5713. napi->timer.function = napi_watchdog;
  5714. init_gro_hash(napi);
  5715. napi->skb = NULL;
  5716. INIT_LIST_HEAD(&napi->rx_list);
  5717. napi->rx_count = 0;
  5718. napi->poll = poll;
  5719. if (weight > NAPI_POLL_WEIGHT)
  5720. netdev_err_once(dev, "%s() called with weight %d\n", __func__,
  5721. weight);
  5722. napi->weight = weight;
  5723. napi->dev = dev;
  5724. #ifdef CONFIG_NETPOLL
  5725. napi->poll_owner = -1;
  5726. #endif
  5727. napi->list_owner = -1;
  5728. set_bit(NAPI_STATE_SCHED, &napi->state);
  5729. set_bit(NAPI_STATE_NPSVC, &napi->state);
  5730. list_add_rcu(&napi->dev_list, &dev->napi_list);
  5731. napi_hash_add(napi);
  5732. napi_get_frags_check(napi);
  5733. /* Create kthread for this napi if dev->threaded is set.
  5734. * Clear dev->threaded if kthread creation failed so that
  5735. * threaded mode will not be enabled in napi_enable().
  5736. */
  5737. if (dev->threaded && napi_kthread_create(napi))
  5738. dev->threaded = false;
  5739. netif_napi_set_irq(napi, -1);
  5740. }
  5741. EXPORT_SYMBOL(netif_napi_add_weight);
  5742. void napi_disable(struct napi_struct *n)
  5743. {
  5744. unsigned long val, new;
  5745. might_sleep();
  5746. set_bit(NAPI_STATE_DISABLE, &n->state);
  5747. val = READ_ONCE(n->state);
  5748. do {
  5749. while (val & (NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC)) {
  5750. usleep_range(20, 200);
  5751. val = READ_ONCE(n->state);
  5752. }
  5753. new = val | NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC;
  5754. new &= ~(NAPIF_STATE_THREADED | NAPIF_STATE_PREFER_BUSY_POLL);
  5755. } while (!try_cmpxchg(&n->state, &val, new));
  5756. hrtimer_cancel(&n->timer);
  5757. clear_bit(NAPI_STATE_DISABLE, &n->state);
  5758. }
  5759. EXPORT_SYMBOL(napi_disable);
  5760. /**
  5761. * napi_enable - enable NAPI scheduling
  5762. * @n: NAPI context
  5763. *
  5764. * Resume NAPI from being scheduled on this context.
  5765. * Must be paired with napi_disable.
  5766. */
  5767. void napi_enable(struct napi_struct *n)
  5768. {
  5769. unsigned long new, val = READ_ONCE(n->state);
  5770. do {
  5771. BUG_ON(!test_bit(NAPI_STATE_SCHED, &val));
  5772. new = val & ~(NAPIF_STATE_SCHED | NAPIF_STATE_NPSVC);
  5773. if (n->dev->threaded && n->thread)
  5774. new |= NAPIF_STATE_THREADED;
  5775. } while (!try_cmpxchg(&n->state, &val, new));
  5776. }
  5777. EXPORT_SYMBOL(napi_enable);
  5778. static void flush_gro_hash(struct napi_struct *napi)
  5779. {
  5780. int i;
  5781. for (i = 0; i < GRO_HASH_BUCKETS; i++) {
  5782. struct sk_buff *skb, *n;
  5783. list_for_each_entry_safe(skb, n, &napi->gro_hash[i].list, list)
  5784. kfree_skb(skb);
  5785. napi->gro_hash[i].count = 0;
  5786. }
  5787. }
  5788. /* Must be called in process context */
  5789. void __netif_napi_del(struct napi_struct *napi)
  5790. {
  5791. if (!test_and_clear_bit(NAPI_STATE_LISTED, &napi->state))
  5792. return;
  5793. napi_hash_del(napi);
  5794. list_del_rcu(&napi->dev_list);
  5795. napi_free_frags(napi);
  5796. flush_gro_hash(napi);
  5797. napi->gro_bitmask = 0;
  5798. if (napi->thread) {
  5799. kthread_stop(napi->thread);
  5800. napi->thread = NULL;
  5801. }
  5802. }
  5803. EXPORT_SYMBOL(__netif_napi_del);
  5804. static int __napi_poll(struct napi_struct *n, bool *repoll)
  5805. {
  5806. int work, weight;
  5807. weight = n->weight;
  5808. /* This NAPI_STATE_SCHED test is for avoiding a race
  5809. * with netpoll's poll_napi(). Only the entity which
  5810. * obtains the lock and sees NAPI_STATE_SCHED set will
  5811. * actually make the ->poll() call. Therefore we avoid
  5812. * accidentally calling ->poll() when NAPI is not scheduled.
  5813. */
  5814. work = 0;
  5815. if (napi_is_scheduled(n)) {
  5816. work = n->poll(n, weight);
  5817. trace_napi_poll(n, work, weight);
  5818. xdp_do_check_flushed(n);
  5819. }
  5820. if (unlikely(work > weight))
  5821. netdev_err_once(n->dev, "NAPI poll function %pS returned %d, exceeding its budget of %d.\n",
  5822. n->poll, work, weight);
  5823. if (likely(work < weight))
  5824. return work;
  5825. /* Drivers must not modify the NAPI state if they
  5826. * consume the entire weight. In such cases this code
  5827. * still "owns" the NAPI instance and therefore can
  5828. * move the instance around on the list at-will.
  5829. */
  5830. if (unlikely(napi_disable_pending(n))) {
  5831. napi_complete(n);
  5832. return work;
  5833. }
  5834. /* The NAPI context has more processing work, but busy-polling
  5835. * is preferred. Exit early.
  5836. */
  5837. if (napi_prefer_busy_poll(n)) {
  5838. if (napi_complete_done(n, work)) {
  5839. /* If timeout is not set, we need to make sure
  5840. * that the NAPI is re-scheduled.
  5841. */
  5842. napi_schedule(n);
  5843. }
  5844. return work;
  5845. }
  5846. if (n->gro_bitmask) {
  5847. /* flush too old packets
  5848. * If HZ < 1000, flush all packets.
  5849. */
  5850. napi_gro_flush(n, HZ >= 1000);
  5851. }
  5852. gro_normal_list(n);
  5853. /* Some drivers may have called napi_schedule
  5854. * prior to exhausting their budget.
  5855. */
  5856. if (unlikely(!list_empty(&n->poll_list))) {
  5857. pr_warn_once("%s: Budget exhausted after napi rescheduled\n",
  5858. n->dev ? n->dev->name : "backlog");
  5859. return work;
  5860. }
  5861. *repoll = true;
  5862. return work;
  5863. }
  5864. static int napi_poll(struct napi_struct *n, struct list_head *repoll)
  5865. {
  5866. bool do_repoll = false;
  5867. void *have;
  5868. int work;
  5869. list_del_init(&n->poll_list);
  5870. have = netpoll_poll_lock(n);
  5871. work = __napi_poll(n, &do_repoll);
  5872. if (do_repoll)
  5873. list_add_tail(&n->poll_list, repoll);
  5874. netpoll_poll_unlock(have);
  5875. return work;
  5876. }
  5877. static int napi_thread_wait(struct napi_struct *napi)
  5878. {
  5879. set_current_state(TASK_INTERRUPTIBLE);
  5880. while (!kthread_should_stop()) {
  5881. /* Testing SCHED_THREADED bit here to make sure the current
  5882. * kthread owns this napi and could poll on this napi.
  5883. * Testing SCHED bit is not enough because SCHED bit might be
  5884. * set by some other busy poll thread or by napi_disable().
  5885. */
  5886. if (test_bit(NAPI_STATE_SCHED_THREADED, &napi->state)) {
  5887. WARN_ON(!list_empty(&napi->poll_list));
  5888. __set_current_state(TASK_RUNNING);
  5889. return 0;
  5890. }
  5891. schedule();
  5892. set_current_state(TASK_INTERRUPTIBLE);
  5893. }
  5894. __set_current_state(TASK_RUNNING);
  5895. return -1;
  5896. }
  5897. static void napi_threaded_poll_loop(struct napi_struct *napi)
  5898. {
  5899. struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
  5900. struct softnet_data *sd;
  5901. unsigned long last_qs = jiffies;
  5902. for (;;) {
  5903. bool repoll = false;
  5904. void *have;
  5905. local_bh_disable();
  5906. bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
  5907. sd = this_cpu_ptr(&softnet_data);
  5908. sd->in_napi_threaded_poll = true;
  5909. have = netpoll_poll_lock(napi);
  5910. __napi_poll(napi, &repoll);
  5911. netpoll_poll_unlock(have);
  5912. sd->in_napi_threaded_poll = false;
  5913. barrier();
  5914. if (sd_has_rps_ipi_waiting(sd)) {
  5915. local_irq_disable();
  5916. net_rps_action_and_irq_enable(sd);
  5917. }
  5918. skb_defer_free_flush(sd);
  5919. bpf_net_ctx_clear(bpf_net_ctx);
  5920. local_bh_enable();
  5921. if (!repoll)
  5922. break;
  5923. rcu_softirq_qs_periodic(last_qs);
  5924. cond_resched();
  5925. }
  5926. }
  5927. static int napi_threaded_poll(void *data)
  5928. {
  5929. struct napi_struct *napi = data;
  5930. while (!napi_thread_wait(napi))
  5931. napi_threaded_poll_loop(napi);
  5932. return 0;
  5933. }
  5934. static __latent_entropy void net_rx_action(void)
  5935. {
  5936. struct softnet_data *sd = this_cpu_ptr(&softnet_data);
  5937. unsigned long time_limit = jiffies +
  5938. usecs_to_jiffies(READ_ONCE(net_hotdata.netdev_budget_usecs));
  5939. struct bpf_net_context __bpf_net_ctx, *bpf_net_ctx;
  5940. int budget = READ_ONCE(net_hotdata.netdev_budget);
  5941. LIST_HEAD(list);
  5942. LIST_HEAD(repoll);
  5943. bpf_net_ctx = bpf_net_ctx_set(&__bpf_net_ctx);
  5944. start:
  5945. sd->in_net_rx_action = true;
  5946. local_irq_disable();
  5947. list_splice_init(&sd->poll_list, &list);
  5948. local_irq_enable();
  5949. for (;;) {
  5950. struct napi_struct *n;
  5951. skb_defer_free_flush(sd);
  5952. if (list_empty(&list)) {
  5953. if (list_empty(&repoll)) {
  5954. sd->in_net_rx_action = false;
  5955. barrier();
  5956. /* We need to check if ____napi_schedule()
  5957. * had refilled poll_list while
  5958. * sd->in_net_rx_action was true.
  5959. */
  5960. if (!list_empty(&sd->poll_list))
  5961. goto start;
  5962. if (!sd_has_rps_ipi_waiting(sd))
  5963. goto end;
  5964. }
  5965. break;
  5966. }
  5967. n = list_first_entry(&list, struct napi_struct, poll_list);
  5968. budget -= napi_poll(n, &repoll);
  5969. /* If softirq window is exhausted then punt.
  5970. * Allow this to run for 2 jiffies since which will allow
  5971. * an average latency of 1.5/HZ.
  5972. */
  5973. if (unlikely(budget <= 0 ||
  5974. time_after_eq(jiffies, time_limit))) {
  5975. sd->time_squeeze++;
  5976. break;
  5977. }
  5978. }
  5979. local_irq_disable();
  5980. list_splice_tail_init(&sd->poll_list, &list);
  5981. list_splice_tail(&repoll, &list);
  5982. list_splice(&list, &sd->poll_list);
  5983. if (!list_empty(&sd->poll_list))
  5984. __raise_softirq_irqoff(NET_RX_SOFTIRQ);
  5985. else
  5986. sd->in_net_rx_action = false;
  5987. net_rps_action_and_irq_enable(sd);
  5988. end:
  5989. bpf_net_ctx_clear(bpf_net_ctx);
  5990. }
  5991. struct netdev_adjacent {
  5992. struct net_device *dev;
  5993. netdevice_tracker dev_tracker;
  5994. /* upper master flag, there can only be one master device per list */
  5995. bool master;
  5996. /* lookup ignore flag */
  5997. bool ignore;
  5998. /* counter for the number of times this device was added to us */
  5999. u16 ref_nr;
  6000. /* private field for the users */
  6001. void *private;
  6002. struct list_head list;
  6003. struct rcu_head rcu;
  6004. };
  6005. static struct netdev_adjacent *__netdev_find_adj(struct net_device *adj_dev,
  6006. struct list_head *adj_list)
  6007. {
  6008. struct netdev_adjacent *adj;
  6009. list_for_each_entry(adj, adj_list, list) {
  6010. if (adj->dev == adj_dev)
  6011. return adj;
  6012. }
  6013. return NULL;
  6014. }
  6015. static int ____netdev_has_upper_dev(struct net_device *upper_dev,
  6016. struct netdev_nested_priv *priv)
  6017. {
  6018. struct net_device *dev = (struct net_device *)priv->data;
  6019. return upper_dev == dev;
  6020. }
  6021. /**
  6022. * netdev_has_upper_dev - Check if device is linked to an upper device
  6023. * @dev: device
  6024. * @upper_dev: upper device to check
  6025. *
  6026. * Find out if a device is linked to specified upper device and return true
  6027. * in case it is. Note that this checks only immediate upper device,
  6028. * not through a complete stack of devices. The caller must hold the RTNL lock.
  6029. */
  6030. bool netdev_has_upper_dev(struct net_device *dev,
  6031. struct net_device *upper_dev)
  6032. {
  6033. struct netdev_nested_priv priv = {
  6034. .data = (void *)upper_dev,
  6035. };
  6036. ASSERT_RTNL();
  6037. return netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
  6038. &priv);
  6039. }
  6040. EXPORT_SYMBOL(netdev_has_upper_dev);
  6041. /**
  6042. * netdev_has_upper_dev_all_rcu - Check if device is linked to an upper device
  6043. * @dev: device
  6044. * @upper_dev: upper device to check
  6045. *
  6046. * Find out if a device is linked to specified upper device and return true
  6047. * in case it is. Note that this checks the entire upper device chain.
  6048. * The caller must hold rcu lock.
  6049. */
  6050. bool netdev_has_upper_dev_all_rcu(struct net_device *dev,
  6051. struct net_device *upper_dev)
  6052. {
  6053. struct netdev_nested_priv priv = {
  6054. .data = (void *)upper_dev,
  6055. };
  6056. return !!netdev_walk_all_upper_dev_rcu(dev, ____netdev_has_upper_dev,
  6057. &priv);
  6058. }
  6059. EXPORT_SYMBOL(netdev_has_upper_dev_all_rcu);
  6060. /**
  6061. * netdev_has_any_upper_dev - Check if device is linked to some device
  6062. * @dev: device
  6063. *
  6064. * Find out if a device is linked to an upper device and return true in case
  6065. * it is. The caller must hold the RTNL lock.
  6066. */
  6067. bool netdev_has_any_upper_dev(struct net_device *dev)
  6068. {
  6069. ASSERT_RTNL();
  6070. return !list_empty(&dev->adj_list.upper);
  6071. }
  6072. EXPORT_SYMBOL(netdev_has_any_upper_dev);
  6073. /**
  6074. * netdev_master_upper_dev_get - Get master upper device
  6075. * @dev: device
  6076. *
  6077. * Find a master upper device and return pointer to it or NULL in case
  6078. * it's not there. The caller must hold the RTNL lock.
  6079. */
  6080. struct net_device *netdev_master_upper_dev_get(struct net_device *dev)
  6081. {
  6082. struct netdev_adjacent *upper;
  6083. ASSERT_RTNL();
  6084. if (list_empty(&dev->adj_list.upper))
  6085. return NULL;
  6086. upper = list_first_entry(&dev->adj_list.upper,
  6087. struct netdev_adjacent, list);
  6088. if (likely(upper->master))
  6089. return upper->dev;
  6090. return NULL;
  6091. }
  6092. EXPORT_SYMBOL(netdev_master_upper_dev_get);
  6093. static struct net_device *__netdev_master_upper_dev_get(struct net_device *dev)
  6094. {
  6095. struct netdev_adjacent *upper;
  6096. ASSERT_RTNL();
  6097. if (list_empty(&dev->adj_list.upper))
  6098. return NULL;
  6099. upper = list_first_entry(&dev->adj_list.upper,
  6100. struct netdev_adjacent, list);
  6101. if (likely(upper->master) && !upper->ignore)
  6102. return upper->dev;
  6103. return NULL;
  6104. }
  6105. /**
  6106. * netdev_has_any_lower_dev - Check if device is linked to some device
  6107. * @dev: device
  6108. *
  6109. * Find out if a device is linked to a lower device and return true in case
  6110. * it is. The caller must hold the RTNL lock.
  6111. */
  6112. static bool netdev_has_any_lower_dev(struct net_device *dev)
  6113. {
  6114. ASSERT_RTNL();
  6115. return !list_empty(&dev->adj_list.lower);
  6116. }
  6117. void *netdev_adjacent_get_private(struct list_head *adj_list)
  6118. {
  6119. struct netdev_adjacent *adj;
  6120. adj = list_entry(adj_list, struct netdev_adjacent, list);
  6121. return adj->private;
  6122. }
  6123. EXPORT_SYMBOL(netdev_adjacent_get_private);
  6124. /**
  6125. * netdev_upper_get_next_dev_rcu - Get the next dev from upper list
  6126. * @dev: device
  6127. * @iter: list_head ** of the current position
  6128. *
  6129. * Gets the next device from the dev's upper list, starting from iter
  6130. * position. The caller must hold RCU read lock.
  6131. */
  6132. struct net_device *netdev_upper_get_next_dev_rcu(struct net_device *dev,
  6133. struct list_head **iter)
  6134. {
  6135. struct netdev_adjacent *upper;
  6136. WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
  6137. upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
  6138. if (&upper->list == &dev->adj_list.upper)
  6139. return NULL;
  6140. *iter = &upper->list;
  6141. return upper->dev;
  6142. }
  6143. EXPORT_SYMBOL(netdev_upper_get_next_dev_rcu);
  6144. static struct net_device *__netdev_next_upper_dev(struct net_device *dev,
  6145. struct list_head **iter,
  6146. bool *ignore)
  6147. {
  6148. struct netdev_adjacent *upper;
  6149. upper = list_entry((*iter)->next, struct netdev_adjacent, list);
  6150. if (&upper->list == &dev->adj_list.upper)
  6151. return NULL;
  6152. *iter = &upper->list;
  6153. *ignore = upper->ignore;
  6154. return upper->dev;
  6155. }
  6156. static struct net_device *netdev_next_upper_dev_rcu(struct net_device *dev,
  6157. struct list_head **iter)
  6158. {
  6159. struct netdev_adjacent *upper;
  6160. WARN_ON_ONCE(!rcu_read_lock_held() && !lockdep_rtnl_is_held());
  6161. upper = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
  6162. if (&upper->list == &dev->adj_list.upper)
  6163. return NULL;
  6164. *iter = &upper->list;
  6165. return upper->dev;
  6166. }
  6167. static int __netdev_walk_all_upper_dev(struct net_device *dev,
  6168. int (*fn)(struct net_device *dev,
  6169. struct netdev_nested_priv *priv),
  6170. struct netdev_nested_priv *priv)
  6171. {
  6172. struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  6173. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  6174. int ret, cur = 0;
  6175. bool ignore;
  6176. now = dev;
  6177. iter = &dev->adj_list.upper;
  6178. while (1) {
  6179. if (now != dev) {
  6180. ret = fn(now, priv);
  6181. if (ret)
  6182. return ret;
  6183. }
  6184. next = NULL;
  6185. while (1) {
  6186. udev = __netdev_next_upper_dev(now, &iter, &ignore);
  6187. if (!udev)
  6188. break;
  6189. if (ignore)
  6190. continue;
  6191. next = udev;
  6192. niter = &udev->adj_list.upper;
  6193. dev_stack[cur] = now;
  6194. iter_stack[cur++] = iter;
  6195. break;
  6196. }
  6197. if (!next) {
  6198. if (!cur)
  6199. return 0;
  6200. next = dev_stack[--cur];
  6201. niter = iter_stack[cur];
  6202. }
  6203. now = next;
  6204. iter = niter;
  6205. }
  6206. return 0;
  6207. }
  6208. int netdev_walk_all_upper_dev_rcu(struct net_device *dev,
  6209. int (*fn)(struct net_device *dev,
  6210. struct netdev_nested_priv *priv),
  6211. struct netdev_nested_priv *priv)
  6212. {
  6213. struct net_device *udev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  6214. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  6215. int ret, cur = 0;
  6216. now = dev;
  6217. iter = &dev->adj_list.upper;
  6218. while (1) {
  6219. if (now != dev) {
  6220. ret = fn(now, priv);
  6221. if (ret)
  6222. return ret;
  6223. }
  6224. next = NULL;
  6225. while (1) {
  6226. udev = netdev_next_upper_dev_rcu(now, &iter);
  6227. if (!udev)
  6228. break;
  6229. next = udev;
  6230. niter = &udev->adj_list.upper;
  6231. dev_stack[cur] = now;
  6232. iter_stack[cur++] = iter;
  6233. break;
  6234. }
  6235. if (!next) {
  6236. if (!cur)
  6237. return 0;
  6238. next = dev_stack[--cur];
  6239. niter = iter_stack[cur];
  6240. }
  6241. now = next;
  6242. iter = niter;
  6243. }
  6244. return 0;
  6245. }
  6246. EXPORT_SYMBOL_GPL(netdev_walk_all_upper_dev_rcu);
  6247. static bool __netdev_has_upper_dev(struct net_device *dev,
  6248. struct net_device *upper_dev)
  6249. {
  6250. struct netdev_nested_priv priv = {
  6251. .flags = 0,
  6252. .data = (void *)upper_dev,
  6253. };
  6254. ASSERT_RTNL();
  6255. return __netdev_walk_all_upper_dev(dev, ____netdev_has_upper_dev,
  6256. &priv);
  6257. }
  6258. /**
  6259. * netdev_lower_get_next_private - Get the next ->private from the
  6260. * lower neighbour list
  6261. * @dev: device
  6262. * @iter: list_head ** of the current position
  6263. *
  6264. * Gets the next netdev_adjacent->private from the dev's lower neighbour
  6265. * list, starting from iter position. The caller must hold either hold the
  6266. * RTNL lock or its own locking that guarantees that the neighbour lower
  6267. * list will remain unchanged.
  6268. */
  6269. void *netdev_lower_get_next_private(struct net_device *dev,
  6270. struct list_head **iter)
  6271. {
  6272. struct netdev_adjacent *lower;
  6273. lower = list_entry(*iter, struct netdev_adjacent, list);
  6274. if (&lower->list == &dev->adj_list.lower)
  6275. return NULL;
  6276. *iter = lower->list.next;
  6277. return lower->private;
  6278. }
  6279. EXPORT_SYMBOL(netdev_lower_get_next_private);
  6280. /**
  6281. * netdev_lower_get_next_private_rcu - Get the next ->private from the
  6282. * lower neighbour list, RCU
  6283. * variant
  6284. * @dev: device
  6285. * @iter: list_head ** of the current position
  6286. *
  6287. * Gets the next netdev_adjacent->private from the dev's lower neighbour
  6288. * list, starting from iter position. The caller must hold RCU read lock.
  6289. */
  6290. void *netdev_lower_get_next_private_rcu(struct net_device *dev,
  6291. struct list_head **iter)
  6292. {
  6293. struct netdev_adjacent *lower;
  6294. WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_bh_held());
  6295. lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
  6296. if (&lower->list == &dev->adj_list.lower)
  6297. return NULL;
  6298. *iter = &lower->list;
  6299. return lower->private;
  6300. }
  6301. EXPORT_SYMBOL(netdev_lower_get_next_private_rcu);
  6302. /**
  6303. * netdev_lower_get_next - Get the next device from the lower neighbour
  6304. * list
  6305. * @dev: device
  6306. * @iter: list_head ** of the current position
  6307. *
  6308. * Gets the next netdev_adjacent from the dev's lower neighbour
  6309. * list, starting from iter position. The caller must hold RTNL lock or
  6310. * its own locking that guarantees that the neighbour lower
  6311. * list will remain unchanged.
  6312. */
  6313. void *netdev_lower_get_next(struct net_device *dev, struct list_head **iter)
  6314. {
  6315. struct netdev_adjacent *lower;
  6316. lower = list_entry(*iter, struct netdev_adjacent, list);
  6317. if (&lower->list == &dev->adj_list.lower)
  6318. return NULL;
  6319. *iter = lower->list.next;
  6320. return lower->dev;
  6321. }
  6322. EXPORT_SYMBOL(netdev_lower_get_next);
  6323. static struct net_device *netdev_next_lower_dev(struct net_device *dev,
  6324. struct list_head **iter)
  6325. {
  6326. struct netdev_adjacent *lower;
  6327. lower = list_entry((*iter)->next, struct netdev_adjacent, list);
  6328. if (&lower->list == &dev->adj_list.lower)
  6329. return NULL;
  6330. *iter = &lower->list;
  6331. return lower->dev;
  6332. }
  6333. static struct net_device *__netdev_next_lower_dev(struct net_device *dev,
  6334. struct list_head **iter,
  6335. bool *ignore)
  6336. {
  6337. struct netdev_adjacent *lower;
  6338. lower = list_entry((*iter)->next, struct netdev_adjacent, list);
  6339. if (&lower->list == &dev->adj_list.lower)
  6340. return NULL;
  6341. *iter = &lower->list;
  6342. *ignore = lower->ignore;
  6343. return lower->dev;
  6344. }
  6345. int netdev_walk_all_lower_dev(struct net_device *dev,
  6346. int (*fn)(struct net_device *dev,
  6347. struct netdev_nested_priv *priv),
  6348. struct netdev_nested_priv *priv)
  6349. {
  6350. struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  6351. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  6352. int ret, cur = 0;
  6353. now = dev;
  6354. iter = &dev->adj_list.lower;
  6355. while (1) {
  6356. if (now != dev) {
  6357. ret = fn(now, priv);
  6358. if (ret)
  6359. return ret;
  6360. }
  6361. next = NULL;
  6362. while (1) {
  6363. ldev = netdev_next_lower_dev(now, &iter);
  6364. if (!ldev)
  6365. break;
  6366. next = ldev;
  6367. niter = &ldev->adj_list.lower;
  6368. dev_stack[cur] = now;
  6369. iter_stack[cur++] = iter;
  6370. break;
  6371. }
  6372. if (!next) {
  6373. if (!cur)
  6374. return 0;
  6375. next = dev_stack[--cur];
  6376. niter = iter_stack[cur];
  6377. }
  6378. now = next;
  6379. iter = niter;
  6380. }
  6381. return 0;
  6382. }
  6383. EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev);
  6384. static int __netdev_walk_all_lower_dev(struct net_device *dev,
  6385. int (*fn)(struct net_device *dev,
  6386. struct netdev_nested_priv *priv),
  6387. struct netdev_nested_priv *priv)
  6388. {
  6389. struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  6390. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  6391. int ret, cur = 0;
  6392. bool ignore;
  6393. now = dev;
  6394. iter = &dev->adj_list.lower;
  6395. while (1) {
  6396. if (now != dev) {
  6397. ret = fn(now, priv);
  6398. if (ret)
  6399. return ret;
  6400. }
  6401. next = NULL;
  6402. while (1) {
  6403. ldev = __netdev_next_lower_dev(now, &iter, &ignore);
  6404. if (!ldev)
  6405. break;
  6406. if (ignore)
  6407. continue;
  6408. next = ldev;
  6409. niter = &ldev->adj_list.lower;
  6410. dev_stack[cur] = now;
  6411. iter_stack[cur++] = iter;
  6412. break;
  6413. }
  6414. if (!next) {
  6415. if (!cur)
  6416. return 0;
  6417. next = dev_stack[--cur];
  6418. niter = iter_stack[cur];
  6419. }
  6420. now = next;
  6421. iter = niter;
  6422. }
  6423. return 0;
  6424. }
  6425. struct net_device *netdev_next_lower_dev_rcu(struct net_device *dev,
  6426. struct list_head **iter)
  6427. {
  6428. struct netdev_adjacent *lower;
  6429. lower = list_entry_rcu((*iter)->next, struct netdev_adjacent, list);
  6430. if (&lower->list == &dev->adj_list.lower)
  6431. return NULL;
  6432. *iter = &lower->list;
  6433. return lower->dev;
  6434. }
  6435. EXPORT_SYMBOL(netdev_next_lower_dev_rcu);
  6436. static u8 __netdev_upper_depth(struct net_device *dev)
  6437. {
  6438. struct net_device *udev;
  6439. struct list_head *iter;
  6440. u8 max_depth = 0;
  6441. bool ignore;
  6442. for (iter = &dev->adj_list.upper,
  6443. udev = __netdev_next_upper_dev(dev, &iter, &ignore);
  6444. udev;
  6445. udev = __netdev_next_upper_dev(dev, &iter, &ignore)) {
  6446. if (ignore)
  6447. continue;
  6448. if (max_depth < udev->upper_level)
  6449. max_depth = udev->upper_level;
  6450. }
  6451. return max_depth;
  6452. }
  6453. static u8 __netdev_lower_depth(struct net_device *dev)
  6454. {
  6455. struct net_device *ldev;
  6456. struct list_head *iter;
  6457. u8 max_depth = 0;
  6458. bool ignore;
  6459. for (iter = &dev->adj_list.lower,
  6460. ldev = __netdev_next_lower_dev(dev, &iter, &ignore);
  6461. ldev;
  6462. ldev = __netdev_next_lower_dev(dev, &iter, &ignore)) {
  6463. if (ignore)
  6464. continue;
  6465. if (max_depth < ldev->lower_level)
  6466. max_depth = ldev->lower_level;
  6467. }
  6468. return max_depth;
  6469. }
  6470. static int __netdev_update_upper_level(struct net_device *dev,
  6471. struct netdev_nested_priv *__unused)
  6472. {
  6473. dev->upper_level = __netdev_upper_depth(dev) + 1;
  6474. return 0;
  6475. }
  6476. #ifdef CONFIG_LOCKDEP
  6477. static LIST_HEAD(net_unlink_list);
  6478. static void net_unlink_todo(struct net_device *dev)
  6479. {
  6480. if (list_empty(&dev->unlink_list))
  6481. list_add_tail(&dev->unlink_list, &net_unlink_list);
  6482. }
  6483. #endif
  6484. static int __netdev_update_lower_level(struct net_device *dev,
  6485. struct netdev_nested_priv *priv)
  6486. {
  6487. dev->lower_level = __netdev_lower_depth(dev) + 1;
  6488. #ifdef CONFIG_LOCKDEP
  6489. if (!priv)
  6490. return 0;
  6491. if (priv->flags & NESTED_SYNC_IMM)
  6492. dev->nested_level = dev->lower_level - 1;
  6493. if (priv->flags & NESTED_SYNC_TODO)
  6494. net_unlink_todo(dev);
  6495. #endif
  6496. return 0;
  6497. }
  6498. int netdev_walk_all_lower_dev_rcu(struct net_device *dev,
  6499. int (*fn)(struct net_device *dev,
  6500. struct netdev_nested_priv *priv),
  6501. struct netdev_nested_priv *priv)
  6502. {
  6503. struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
  6504. struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
  6505. int ret, cur = 0;
  6506. now = dev;
  6507. iter = &dev->adj_list.lower;
  6508. while (1) {
  6509. if (now != dev) {
  6510. ret = fn(now, priv);
  6511. if (ret)
  6512. return ret;
  6513. }
  6514. next = NULL;
  6515. while (1) {
  6516. ldev = netdev_next_lower_dev_rcu(now, &iter);
  6517. if (!ldev)
  6518. break;
  6519. next = ldev;
  6520. niter = &ldev->adj_list.lower;
  6521. dev_stack[cur] = now;
  6522. iter_stack[cur++] = iter;
  6523. break;
  6524. }
  6525. if (!next) {
  6526. if (!cur)
  6527. return 0;
  6528. next = dev_stack[--cur];
  6529. niter = iter_stack[cur];
  6530. }
  6531. now = next;
  6532. iter = niter;
  6533. }
  6534. return 0;
  6535. }
  6536. EXPORT_SYMBOL_GPL(netdev_walk_all_lower_dev_rcu);
  6537. /**
  6538. * netdev_lower_get_first_private_rcu - Get the first ->private from the
  6539. * lower neighbour list, RCU
  6540. * variant
  6541. * @dev: device
  6542. *
  6543. * Gets the first netdev_adjacent->private from the dev's lower neighbour
  6544. * list. The caller must hold RCU read lock.
  6545. */
  6546. void *netdev_lower_get_first_private_rcu(struct net_device *dev)
  6547. {
  6548. struct netdev_adjacent *lower;
  6549. lower = list_first_or_null_rcu(&dev->adj_list.lower,
  6550. struct netdev_adjacent, list);
  6551. if (lower)
  6552. return lower->private;
  6553. return NULL;
  6554. }
  6555. EXPORT_SYMBOL(netdev_lower_get_first_private_rcu);
  6556. /**
  6557. * netdev_master_upper_dev_get_rcu - Get master upper device
  6558. * @dev: device
  6559. *
  6560. * Find a master upper device and return pointer to it or NULL in case
  6561. * it's not there. The caller must hold the RCU read lock.
  6562. */
  6563. struct net_device *netdev_master_upper_dev_get_rcu(struct net_device *dev)
  6564. {
  6565. struct netdev_adjacent *upper;
  6566. upper = list_first_or_null_rcu(&dev->adj_list.upper,
  6567. struct netdev_adjacent, list);
  6568. if (upper && likely(upper->master))
  6569. return upper->dev;
  6570. return NULL;
  6571. }
  6572. EXPORT_SYMBOL(netdev_master_upper_dev_get_rcu);
  6573. static int netdev_adjacent_sysfs_add(struct net_device *dev,
  6574. struct net_device *adj_dev,
  6575. struct list_head *dev_list)
  6576. {
  6577. char linkname[IFNAMSIZ+7];
  6578. sprintf(linkname, dev_list == &dev->adj_list.upper ?
  6579. "upper_%s" : "lower_%s", adj_dev->name);
  6580. return sysfs_create_link(&(dev->dev.kobj), &(adj_dev->dev.kobj),
  6581. linkname);
  6582. }
  6583. static void netdev_adjacent_sysfs_del(struct net_device *dev,
  6584. char *name,
  6585. struct list_head *dev_list)
  6586. {
  6587. char linkname[IFNAMSIZ+7];
  6588. sprintf(linkname, dev_list == &dev->adj_list.upper ?
  6589. "upper_%s" : "lower_%s", name);
  6590. sysfs_remove_link(&(dev->dev.kobj), linkname);
  6591. }
  6592. static inline bool netdev_adjacent_is_neigh_list(struct net_device *dev,
  6593. struct net_device *adj_dev,
  6594. struct list_head *dev_list)
  6595. {
  6596. return (dev_list == &dev->adj_list.upper ||
  6597. dev_list == &dev->adj_list.lower) &&
  6598. net_eq(dev_net(dev), dev_net(adj_dev));
  6599. }
  6600. static int __netdev_adjacent_dev_insert(struct net_device *dev,
  6601. struct net_device *adj_dev,
  6602. struct list_head *dev_list,
  6603. void *private, bool master)
  6604. {
  6605. struct netdev_adjacent *adj;
  6606. int ret;
  6607. adj = __netdev_find_adj(adj_dev, dev_list);
  6608. if (adj) {
  6609. adj->ref_nr += 1;
  6610. pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d\n",
  6611. dev->name, adj_dev->name, adj->ref_nr);
  6612. return 0;
  6613. }
  6614. adj = kmalloc(sizeof(*adj), GFP_KERNEL);
  6615. if (!adj)
  6616. return -ENOMEM;
  6617. adj->dev = adj_dev;
  6618. adj->master = master;
  6619. adj->ref_nr = 1;
  6620. adj->private = private;
  6621. adj->ignore = false;
  6622. netdev_hold(adj_dev, &adj->dev_tracker, GFP_KERNEL);
  6623. pr_debug("Insert adjacency: dev %s adj_dev %s adj->ref_nr %d; dev_hold on %s\n",
  6624. dev->name, adj_dev->name, adj->ref_nr, adj_dev->name);
  6625. if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list)) {
  6626. ret = netdev_adjacent_sysfs_add(dev, adj_dev, dev_list);
  6627. if (ret)
  6628. goto free_adj;
  6629. }
  6630. /* Ensure that master link is always the first item in list. */
  6631. if (master) {
  6632. ret = sysfs_create_link(&(dev->dev.kobj),
  6633. &(adj_dev->dev.kobj), "master");
  6634. if (ret)
  6635. goto remove_symlinks;
  6636. list_add_rcu(&adj->list, dev_list);
  6637. } else {
  6638. list_add_tail_rcu(&adj->list, dev_list);
  6639. }
  6640. return 0;
  6641. remove_symlinks:
  6642. if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
  6643. netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
  6644. free_adj:
  6645. netdev_put(adj_dev, &adj->dev_tracker);
  6646. kfree(adj);
  6647. return ret;
  6648. }
  6649. static void __netdev_adjacent_dev_remove(struct net_device *dev,
  6650. struct net_device *adj_dev,
  6651. u16 ref_nr,
  6652. struct list_head *dev_list)
  6653. {
  6654. struct netdev_adjacent *adj;
  6655. pr_debug("Remove adjacency: dev %s adj_dev %s ref_nr %d\n",
  6656. dev->name, adj_dev->name, ref_nr);
  6657. adj = __netdev_find_adj(adj_dev, dev_list);
  6658. if (!adj) {
  6659. pr_err("Adjacency does not exist for device %s from %s\n",
  6660. dev->name, adj_dev->name);
  6661. WARN_ON(1);
  6662. return;
  6663. }
  6664. if (adj->ref_nr > ref_nr) {
  6665. pr_debug("adjacency: %s to %s ref_nr - %d = %d\n",
  6666. dev->name, adj_dev->name, ref_nr,
  6667. adj->ref_nr - ref_nr);
  6668. adj->ref_nr -= ref_nr;
  6669. return;
  6670. }
  6671. if (adj->master)
  6672. sysfs_remove_link(&(dev->dev.kobj), "master");
  6673. if (netdev_adjacent_is_neigh_list(dev, adj_dev, dev_list))
  6674. netdev_adjacent_sysfs_del(dev, adj_dev->name, dev_list);
  6675. list_del_rcu(&adj->list);
  6676. pr_debug("adjacency: dev_put for %s, because link removed from %s to %s\n",
  6677. adj_dev->name, dev->name, adj_dev->name);
  6678. netdev_put(adj_dev, &adj->dev_tracker);
  6679. kfree_rcu(adj, rcu);
  6680. }
  6681. static int __netdev_adjacent_dev_link_lists(struct net_device *dev,
  6682. struct net_device *upper_dev,
  6683. struct list_head *up_list,
  6684. struct list_head *down_list,
  6685. void *private, bool master)
  6686. {
  6687. int ret;
  6688. ret = __netdev_adjacent_dev_insert(dev, upper_dev, up_list,
  6689. private, master);
  6690. if (ret)
  6691. return ret;
  6692. ret = __netdev_adjacent_dev_insert(upper_dev, dev, down_list,
  6693. private, false);
  6694. if (ret) {
  6695. __netdev_adjacent_dev_remove(dev, upper_dev, 1, up_list);
  6696. return ret;
  6697. }
  6698. return 0;
  6699. }
  6700. static void __netdev_adjacent_dev_unlink_lists(struct net_device *dev,
  6701. struct net_device *upper_dev,
  6702. u16 ref_nr,
  6703. struct list_head *up_list,
  6704. struct list_head *down_list)
  6705. {
  6706. __netdev_adjacent_dev_remove(dev, upper_dev, ref_nr, up_list);
  6707. __netdev_adjacent_dev_remove(upper_dev, dev, ref_nr, down_list);
  6708. }
  6709. static int __netdev_adjacent_dev_link_neighbour(struct net_device *dev,
  6710. struct net_device *upper_dev,
  6711. void *private, bool master)
  6712. {
  6713. return __netdev_adjacent_dev_link_lists(dev, upper_dev,
  6714. &dev->adj_list.upper,
  6715. &upper_dev->adj_list.lower,
  6716. private, master);
  6717. }
  6718. static void __netdev_adjacent_dev_unlink_neighbour(struct net_device *dev,
  6719. struct net_device *upper_dev)
  6720. {
  6721. __netdev_adjacent_dev_unlink_lists(dev, upper_dev, 1,
  6722. &dev->adj_list.upper,
  6723. &upper_dev->adj_list.lower);
  6724. }
  6725. static int __netdev_upper_dev_link(struct net_device *dev,
  6726. struct net_device *upper_dev, bool master,
  6727. void *upper_priv, void *upper_info,
  6728. struct netdev_nested_priv *priv,
  6729. struct netlink_ext_ack *extack)
  6730. {
  6731. struct netdev_notifier_changeupper_info changeupper_info = {
  6732. .info = {
  6733. .dev = dev,
  6734. .extack = extack,
  6735. },
  6736. .upper_dev = upper_dev,
  6737. .master = master,
  6738. .linking = true,
  6739. .upper_info = upper_info,
  6740. };
  6741. struct net_device *master_dev;
  6742. int ret = 0;
  6743. ASSERT_RTNL();
  6744. if (dev == upper_dev)
  6745. return -EBUSY;
  6746. /* To prevent loops, check if dev is not upper device to upper_dev. */
  6747. if (__netdev_has_upper_dev(upper_dev, dev))
  6748. return -EBUSY;
  6749. if ((dev->lower_level + upper_dev->upper_level) > MAX_NEST_DEV)
  6750. return -EMLINK;
  6751. if (!master) {
  6752. if (__netdev_has_upper_dev(dev, upper_dev))
  6753. return -EEXIST;
  6754. } else {
  6755. master_dev = __netdev_master_upper_dev_get(dev);
  6756. if (master_dev)
  6757. return master_dev == upper_dev ? -EEXIST : -EBUSY;
  6758. }
  6759. ret = call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
  6760. &changeupper_info.info);
  6761. ret = notifier_to_errno(ret);
  6762. if (ret)
  6763. return ret;
  6764. ret = __netdev_adjacent_dev_link_neighbour(dev, upper_dev, upper_priv,
  6765. master);
  6766. if (ret)
  6767. return ret;
  6768. ret = call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
  6769. &changeupper_info.info);
  6770. ret = notifier_to_errno(ret);
  6771. if (ret)
  6772. goto rollback;
  6773. __netdev_update_upper_level(dev, NULL);
  6774. __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
  6775. __netdev_update_lower_level(upper_dev, priv);
  6776. __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
  6777. priv);
  6778. return 0;
  6779. rollback:
  6780. __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
  6781. return ret;
  6782. }
  6783. /**
  6784. * netdev_upper_dev_link - Add a link to the upper device
  6785. * @dev: device
  6786. * @upper_dev: new upper device
  6787. * @extack: netlink extended ack
  6788. *
  6789. * Adds a link to device which is upper to this one. The caller must hold
  6790. * the RTNL lock. On a failure a negative errno code is returned.
  6791. * On success the reference counts are adjusted and the function
  6792. * returns zero.
  6793. */
  6794. int netdev_upper_dev_link(struct net_device *dev,
  6795. struct net_device *upper_dev,
  6796. struct netlink_ext_ack *extack)
  6797. {
  6798. struct netdev_nested_priv priv = {
  6799. .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
  6800. .data = NULL,
  6801. };
  6802. return __netdev_upper_dev_link(dev, upper_dev, false,
  6803. NULL, NULL, &priv, extack);
  6804. }
  6805. EXPORT_SYMBOL(netdev_upper_dev_link);
  6806. /**
  6807. * netdev_master_upper_dev_link - Add a master link to the upper device
  6808. * @dev: device
  6809. * @upper_dev: new upper device
  6810. * @upper_priv: upper device private
  6811. * @upper_info: upper info to be passed down via notifier
  6812. * @extack: netlink extended ack
  6813. *
  6814. * Adds a link to device which is upper to this one. In this case, only
  6815. * one master upper device can be linked, although other non-master devices
  6816. * might be linked as well. The caller must hold the RTNL lock.
  6817. * On a failure a negative errno code is returned. On success the reference
  6818. * counts are adjusted and the function returns zero.
  6819. */
  6820. int netdev_master_upper_dev_link(struct net_device *dev,
  6821. struct net_device *upper_dev,
  6822. void *upper_priv, void *upper_info,
  6823. struct netlink_ext_ack *extack)
  6824. {
  6825. struct netdev_nested_priv priv = {
  6826. .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
  6827. .data = NULL,
  6828. };
  6829. return __netdev_upper_dev_link(dev, upper_dev, true,
  6830. upper_priv, upper_info, &priv, extack);
  6831. }
  6832. EXPORT_SYMBOL(netdev_master_upper_dev_link);
  6833. static void __netdev_upper_dev_unlink(struct net_device *dev,
  6834. struct net_device *upper_dev,
  6835. struct netdev_nested_priv *priv)
  6836. {
  6837. struct netdev_notifier_changeupper_info changeupper_info = {
  6838. .info = {
  6839. .dev = dev,
  6840. },
  6841. .upper_dev = upper_dev,
  6842. .linking = false,
  6843. };
  6844. ASSERT_RTNL();
  6845. changeupper_info.master = netdev_master_upper_dev_get(dev) == upper_dev;
  6846. call_netdevice_notifiers_info(NETDEV_PRECHANGEUPPER,
  6847. &changeupper_info.info);
  6848. __netdev_adjacent_dev_unlink_neighbour(dev, upper_dev);
  6849. call_netdevice_notifiers_info(NETDEV_CHANGEUPPER,
  6850. &changeupper_info.info);
  6851. __netdev_update_upper_level(dev, NULL);
  6852. __netdev_walk_all_lower_dev(dev, __netdev_update_upper_level, NULL);
  6853. __netdev_update_lower_level(upper_dev, priv);
  6854. __netdev_walk_all_upper_dev(upper_dev, __netdev_update_lower_level,
  6855. priv);
  6856. }
  6857. /**
  6858. * netdev_upper_dev_unlink - Removes a link to upper device
  6859. * @dev: device
  6860. * @upper_dev: new upper device
  6861. *
  6862. * Removes a link to device which is upper to this one. The caller must hold
  6863. * the RTNL lock.
  6864. */
  6865. void netdev_upper_dev_unlink(struct net_device *dev,
  6866. struct net_device *upper_dev)
  6867. {
  6868. struct netdev_nested_priv priv = {
  6869. .flags = NESTED_SYNC_TODO,
  6870. .data = NULL,
  6871. };
  6872. __netdev_upper_dev_unlink(dev, upper_dev, &priv);
  6873. }
  6874. EXPORT_SYMBOL(netdev_upper_dev_unlink);
  6875. static void __netdev_adjacent_dev_set(struct net_device *upper_dev,
  6876. struct net_device *lower_dev,
  6877. bool val)
  6878. {
  6879. struct netdev_adjacent *adj;
  6880. adj = __netdev_find_adj(lower_dev, &upper_dev->adj_list.lower);
  6881. if (adj)
  6882. adj->ignore = val;
  6883. adj = __netdev_find_adj(upper_dev, &lower_dev->adj_list.upper);
  6884. if (adj)
  6885. adj->ignore = val;
  6886. }
  6887. static void netdev_adjacent_dev_disable(struct net_device *upper_dev,
  6888. struct net_device *lower_dev)
  6889. {
  6890. __netdev_adjacent_dev_set(upper_dev, lower_dev, true);
  6891. }
  6892. static void netdev_adjacent_dev_enable(struct net_device *upper_dev,
  6893. struct net_device *lower_dev)
  6894. {
  6895. __netdev_adjacent_dev_set(upper_dev, lower_dev, false);
  6896. }
  6897. int netdev_adjacent_change_prepare(struct net_device *old_dev,
  6898. struct net_device *new_dev,
  6899. struct net_device *dev,
  6900. struct netlink_ext_ack *extack)
  6901. {
  6902. struct netdev_nested_priv priv = {
  6903. .flags = 0,
  6904. .data = NULL,
  6905. };
  6906. int err;
  6907. if (!new_dev)
  6908. return 0;
  6909. if (old_dev && new_dev != old_dev)
  6910. netdev_adjacent_dev_disable(dev, old_dev);
  6911. err = __netdev_upper_dev_link(new_dev, dev, false, NULL, NULL, &priv,
  6912. extack);
  6913. if (err) {
  6914. if (old_dev && new_dev != old_dev)
  6915. netdev_adjacent_dev_enable(dev, old_dev);
  6916. return err;
  6917. }
  6918. return 0;
  6919. }
  6920. EXPORT_SYMBOL(netdev_adjacent_change_prepare);
  6921. void netdev_adjacent_change_commit(struct net_device *old_dev,
  6922. struct net_device *new_dev,
  6923. struct net_device *dev)
  6924. {
  6925. struct netdev_nested_priv priv = {
  6926. .flags = NESTED_SYNC_IMM | NESTED_SYNC_TODO,
  6927. .data = NULL,
  6928. };
  6929. if (!new_dev || !old_dev)
  6930. return;
  6931. if (new_dev == old_dev)
  6932. return;
  6933. netdev_adjacent_dev_enable(dev, old_dev);
  6934. __netdev_upper_dev_unlink(old_dev, dev, &priv);
  6935. }
  6936. EXPORT_SYMBOL(netdev_adjacent_change_commit);
  6937. void netdev_adjacent_change_abort(struct net_device *old_dev,
  6938. struct net_device *new_dev,
  6939. struct net_device *dev)
  6940. {
  6941. struct netdev_nested_priv priv = {
  6942. .flags = 0,
  6943. .data = NULL,
  6944. };
  6945. if (!new_dev)
  6946. return;
  6947. if (old_dev && new_dev != old_dev)
  6948. netdev_adjacent_dev_enable(dev, old_dev);
  6949. __netdev_upper_dev_unlink(new_dev, dev, &priv);
  6950. }
  6951. EXPORT_SYMBOL(netdev_adjacent_change_abort);
  6952. /**
  6953. * netdev_bonding_info_change - Dispatch event about slave change
  6954. * @dev: device
  6955. * @bonding_info: info to dispatch
  6956. *
  6957. * Send NETDEV_BONDING_INFO to netdev notifiers with info.
  6958. * The caller must hold the RTNL lock.
  6959. */
  6960. void netdev_bonding_info_change(struct net_device *dev,
  6961. struct netdev_bonding_info *bonding_info)
  6962. {
  6963. struct netdev_notifier_bonding_info info = {
  6964. .info.dev = dev,
  6965. };
  6966. memcpy(&info.bonding_info, bonding_info,
  6967. sizeof(struct netdev_bonding_info));
  6968. call_netdevice_notifiers_info(NETDEV_BONDING_INFO,
  6969. &info.info);
  6970. }
  6971. EXPORT_SYMBOL(netdev_bonding_info_change);
  6972. static int netdev_offload_xstats_enable_l3(struct net_device *dev,
  6973. struct netlink_ext_ack *extack)
  6974. {
  6975. struct netdev_notifier_offload_xstats_info info = {
  6976. .info.dev = dev,
  6977. .info.extack = extack,
  6978. .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
  6979. };
  6980. int err;
  6981. int rc;
  6982. dev->offload_xstats_l3 = kzalloc(sizeof(*dev->offload_xstats_l3),
  6983. GFP_KERNEL);
  6984. if (!dev->offload_xstats_l3)
  6985. return -ENOMEM;
  6986. rc = call_netdevice_notifiers_info_robust(NETDEV_OFFLOAD_XSTATS_ENABLE,
  6987. NETDEV_OFFLOAD_XSTATS_DISABLE,
  6988. &info.info);
  6989. err = notifier_to_errno(rc);
  6990. if (err)
  6991. goto free_stats;
  6992. return 0;
  6993. free_stats:
  6994. kfree(dev->offload_xstats_l3);
  6995. dev->offload_xstats_l3 = NULL;
  6996. return err;
  6997. }
  6998. int netdev_offload_xstats_enable(struct net_device *dev,
  6999. enum netdev_offload_xstats_type type,
  7000. struct netlink_ext_ack *extack)
  7001. {
  7002. ASSERT_RTNL();
  7003. if (netdev_offload_xstats_enabled(dev, type))
  7004. return -EALREADY;
  7005. switch (type) {
  7006. case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
  7007. return netdev_offload_xstats_enable_l3(dev, extack);
  7008. }
  7009. WARN_ON(1);
  7010. return -EINVAL;
  7011. }
  7012. EXPORT_SYMBOL(netdev_offload_xstats_enable);
  7013. static void netdev_offload_xstats_disable_l3(struct net_device *dev)
  7014. {
  7015. struct netdev_notifier_offload_xstats_info info = {
  7016. .info.dev = dev,
  7017. .type = NETDEV_OFFLOAD_XSTATS_TYPE_L3,
  7018. };
  7019. call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_DISABLE,
  7020. &info.info);
  7021. kfree(dev->offload_xstats_l3);
  7022. dev->offload_xstats_l3 = NULL;
  7023. }
  7024. int netdev_offload_xstats_disable(struct net_device *dev,
  7025. enum netdev_offload_xstats_type type)
  7026. {
  7027. ASSERT_RTNL();
  7028. if (!netdev_offload_xstats_enabled(dev, type))
  7029. return -EALREADY;
  7030. switch (type) {
  7031. case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
  7032. netdev_offload_xstats_disable_l3(dev);
  7033. return 0;
  7034. }
  7035. WARN_ON(1);
  7036. return -EINVAL;
  7037. }
  7038. EXPORT_SYMBOL(netdev_offload_xstats_disable);
  7039. static void netdev_offload_xstats_disable_all(struct net_device *dev)
  7040. {
  7041. netdev_offload_xstats_disable(dev, NETDEV_OFFLOAD_XSTATS_TYPE_L3);
  7042. }
  7043. static struct rtnl_hw_stats64 *
  7044. netdev_offload_xstats_get_ptr(const struct net_device *dev,
  7045. enum netdev_offload_xstats_type type)
  7046. {
  7047. switch (type) {
  7048. case NETDEV_OFFLOAD_XSTATS_TYPE_L3:
  7049. return dev->offload_xstats_l3;
  7050. }
  7051. WARN_ON(1);
  7052. return NULL;
  7053. }
  7054. bool netdev_offload_xstats_enabled(const struct net_device *dev,
  7055. enum netdev_offload_xstats_type type)
  7056. {
  7057. ASSERT_RTNL();
  7058. return netdev_offload_xstats_get_ptr(dev, type);
  7059. }
  7060. EXPORT_SYMBOL(netdev_offload_xstats_enabled);
  7061. struct netdev_notifier_offload_xstats_ru {
  7062. bool used;
  7063. };
  7064. struct netdev_notifier_offload_xstats_rd {
  7065. struct rtnl_hw_stats64 stats;
  7066. bool used;
  7067. };
  7068. static void netdev_hw_stats64_add(struct rtnl_hw_stats64 *dest,
  7069. const struct rtnl_hw_stats64 *src)
  7070. {
  7071. dest->rx_packets += src->rx_packets;
  7072. dest->tx_packets += src->tx_packets;
  7073. dest->rx_bytes += src->rx_bytes;
  7074. dest->tx_bytes += src->tx_bytes;
  7075. dest->rx_errors += src->rx_errors;
  7076. dest->tx_errors += src->tx_errors;
  7077. dest->rx_dropped += src->rx_dropped;
  7078. dest->tx_dropped += src->tx_dropped;
  7079. dest->multicast += src->multicast;
  7080. }
  7081. static int netdev_offload_xstats_get_used(struct net_device *dev,
  7082. enum netdev_offload_xstats_type type,
  7083. bool *p_used,
  7084. struct netlink_ext_ack *extack)
  7085. {
  7086. struct netdev_notifier_offload_xstats_ru report_used = {};
  7087. struct netdev_notifier_offload_xstats_info info = {
  7088. .info.dev = dev,
  7089. .info.extack = extack,
  7090. .type = type,
  7091. .report_used = &report_used,
  7092. };
  7093. int rc;
  7094. WARN_ON(!netdev_offload_xstats_enabled(dev, type));
  7095. rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_USED,
  7096. &info.info);
  7097. *p_used = report_used.used;
  7098. return notifier_to_errno(rc);
  7099. }
  7100. static int netdev_offload_xstats_get_stats(struct net_device *dev,
  7101. enum netdev_offload_xstats_type type,
  7102. struct rtnl_hw_stats64 *p_stats,
  7103. bool *p_used,
  7104. struct netlink_ext_ack *extack)
  7105. {
  7106. struct netdev_notifier_offload_xstats_rd report_delta = {};
  7107. struct netdev_notifier_offload_xstats_info info = {
  7108. .info.dev = dev,
  7109. .info.extack = extack,
  7110. .type = type,
  7111. .report_delta = &report_delta,
  7112. };
  7113. struct rtnl_hw_stats64 *stats;
  7114. int rc;
  7115. stats = netdev_offload_xstats_get_ptr(dev, type);
  7116. if (WARN_ON(!stats))
  7117. return -EINVAL;
  7118. rc = call_netdevice_notifiers_info(NETDEV_OFFLOAD_XSTATS_REPORT_DELTA,
  7119. &info.info);
  7120. /* Cache whatever we got, even if there was an error, otherwise the
  7121. * successful stats retrievals would get lost.
  7122. */
  7123. netdev_hw_stats64_add(stats, &report_delta.stats);
  7124. if (p_stats)
  7125. *p_stats = *stats;
  7126. *p_used = report_delta.used;
  7127. return notifier_to_errno(rc);
  7128. }
  7129. int netdev_offload_xstats_get(struct net_device *dev,
  7130. enum netdev_offload_xstats_type type,
  7131. struct rtnl_hw_stats64 *p_stats, bool *p_used,
  7132. struct netlink_ext_ack *extack)
  7133. {
  7134. ASSERT_RTNL();
  7135. if (p_stats)
  7136. return netdev_offload_xstats_get_stats(dev, type, p_stats,
  7137. p_used, extack);
  7138. else
  7139. return netdev_offload_xstats_get_used(dev, type, p_used,
  7140. extack);
  7141. }
  7142. EXPORT_SYMBOL(netdev_offload_xstats_get);
  7143. void
  7144. netdev_offload_xstats_report_delta(struct netdev_notifier_offload_xstats_rd *report_delta,
  7145. const struct rtnl_hw_stats64 *stats)
  7146. {
  7147. report_delta->used = true;
  7148. netdev_hw_stats64_add(&report_delta->stats, stats);
  7149. }
  7150. EXPORT_SYMBOL(netdev_offload_xstats_report_delta);
  7151. void
  7152. netdev_offload_xstats_report_used(struct netdev_notifier_offload_xstats_ru *report_used)
  7153. {
  7154. report_used->used = true;
  7155. }
  7156. EXPORT_SYMBOL(netdev_offload_xstats_report_used);
  7157. void netdev_offload_xstats_push_delta(struct net_device *dev,
  7158. enum netdev_offload_xstats_type type,
  7159. const struct rtnl_hw_stats64 *p_stats)
  7160. {
  7161. struct rtnl_hw_stats64 *stats;
  7162. ASSERT_RTNL();
  7163. stats = netdev_offload_xstats_get_ptr(dev, type);
  7164. if (WARN_ON(!stats))
  7165. return;
  7166. netdev_hw_stats64_add(stats, p_stats);
  7167. }
  7168. EXPORT_SYMBOL(netdev_offload_xstats_push_delta);
  7169. /**
  7170. * netdev_get_xmit_slave - Get the xmit slave of master device
  7171. * @dev: device
  7172. * @skb: The packet
  7173. * @all_slaves: assume all the slaves are active
  7174. *
  7175. * The reference counters are not incremented so the caller must be
  7176. * careful with locks. The caller must hold RCU lock.
  7177. * %NULL is returned if no slave is found.
  7178. */
  7179. struct net_device *netdev_get_xmit_slave(struct net_device *dev,
  7180. struct sk_buff *skb,
  7181. bool all_slaves)
  7182. {
  7183. const struct net_device_ops *ops = dev->netdev_ops;
  7184. if (!ops->ndo_get_xmit_slave)
  7185. return NULL;
  7186. return ops->ndo_get_xmit_slave(dev, skb, all_slaves);
  7187. }
  7188. EXPORT_SYMBOL(netdev_get_xmit_slave);
  7189. static struct net_device *netdev_sk_get_lower_dev(struct net_device *dev,
  7190. struct sock *sk)
  7191. {
  7192. const struct net_device_ops *ops = dev->netdev_ops;
  7193. if (!ops->ndo_sk_get_lower_dev)
  7194. return NULL;
  7195. return ops->ndo_sk_get_lower_dev(dev, sk);
  7196. }
  7197. /**
  7198. * netdev_sk_get_lowest_dev - Get the lowest device in chain given device and socket
  7199. * @dev: device
  7200. * @sk: the socket
  7201. *
  7202. * %NULL is returned if no lower device is found.
  7203. */
  7204. struct net_device *netdev_sk_get_lowest_dev(struct net_device *dev,
  7205. struct sock *sk)
  7206. {
  7207. struct net_device *lower;
  7208. lower = netdev_sk_get_lower_dev(dev, sk);
  7209. while (lower) {
  7210. dev = lower;
  7211. lower = netdev_sk_get_lower_dev(dev, sk);
  7212. }
  7213. return dev;
  7214. }
  7215. EXPORT_SYMBOL(netdev_sk_get_lowest_dev);
  7216. static void netdev_adjacent_add_links(struct net_device *dev)
  7217. {
  7218. struct netdev_adjacent *iter;
  7219. struct net *net = dev_net(dev);
  7220. list_for_each_entry(iter, &dev->adj_list.upper, list) {
  7221. if (!net_eq(net, dev_net(iter->dev)))
  7222. continue;
  7223. netdev_adjacent_sysfs_add(iter->dev, dev,
  7224. &iter->dev->adj_list.lower);
  7225. netdev_adjacent_sysfs_add(dev, iter->dev,
  7226. &dev->adj_list.upper);
  7227. }
  7228. list_for_each_entry(iter, &dev->adj_list.lower, list) {
  7229. if (!net_eq(net, dev_net(iter->dev)))
  7230. continue;
  7231. netdev_adjacent_sysfs_add(iter->dev, dev,
  7232. &iter->dev->adj_list.upper);
  7233. netdev_adjacent_sysfs_add(dev, iter->dev,
  7234. &dev->adj_list.lower);
  7235. }
  7236. }
  7237. static void netdev_adjacent_del_links(struct net_device *dev)
  7238. {
  7239. struct netdev_adjacent *iter;
  7240. struct net *net = dev_net(dev);
  7241. list_for_each_entry(iter, &dev->adj_list.upper, list) {
  7242. if (!net_eq(net, dev_net(iter->dev)))
  7243. continue;
  7244. netdev_adjacent_sysfs_del(iter->dev, dev->name,
  7245. &iter->dev->adj_list.lower);
  7246. netdev_adjacent_sysfs_del(dev, iter->dev->name,
  7247. &dev->adj_list.upper);
  7248. }
  7249. list_for_each_entry(iter, &dev->adj_list.lower, list) {
  7250. if (!net_eq(net, dev_net(iter->dev)))
  7251. continue;
  7252. netdev_adjacent_sysfs_del(iter->dev, dev->name,
  7253. &iter->dev->adj_list.upper);
  7254. netdev_adjacent_sysfs_del(dev, iter->dev->name,
  7255. &dev->adj_list.lower);
  7256. }
  7257. }
  7258. void netdev_adjacent_rename_links(struct net_device *dev, char *oldname)
  7259. {
  7260. struct netdev_adjacent *iter;
  7261. struct net *net = dev_net(dev);
  7262. list_for_each_entry(iter, &dev->adj_list.upper, list) {
  7263. if (!net_eq(net, dev_net(iter->dev)))
  7264. continue;
  7265. netdev_adjacent_sysfs_del(iter->dev, oldname,
  7266. &iter->dev->adj_list.lower);
  7267. netdev_adjacent_sysfs_add(iter->dev, dev,
  7268. &iter->dev->adj_list.lower);
  7269. }
  7270. list_for_each_entry(iter, &dev->adj_list.lower, list) {
  7271. if (!net_eq(net, dev_net(iter->dev)))
  7272. continue;
  7273. netdev_adjacent_sysfs_del(iter->dev, oldname,
  7274. &iter->dev->adj_list.upper);
  7275. netdev_adjacent_sysfs_add(iter->dev, dev,
  7276. &iter->dev->adj_list.upper);
  7277. }
  7278. }
  7279. void *netdev_lower_dev_get_private(struct net_device *dev,
  7280. struct net_device *lower_dev)
  7281. {
  7282. struct netdev_adjacent *lower;
  7283. if (!lower_dev)
  7284. return NULL;
  7285. lower = __netdev_find_adj(lower_dev, &dev->adj_list.lower);
  7286. if (!lower)
  7287. return NULL;
  7288. return lower->private;
  7289. }
  7290. EXPORT_SYMBOL(netdev_lower_dev_get_private);
  7291. /**
  7292. * netdev_lower_state_changed - Dispatch event about lower device state change
  7293. * @lower_dev: device
  7294. * @lower_state_info: state to dispatch
  7295. *
  7296. * Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info.
  7297. * The caller must hold the RTNL lock.
  7298. */
  7299. void netdev_lower_state_changed(struct net_device *lower_dev,
  7300. void *lower_state_info)
  7301. {
  7302. struct netdev_notifier_changelowerstate_info changelowerstate_info = {
  7303. .info.dev = lower_dev,
  7304. };
  7305. ASSERT_RTNL();
  7306. changelowerstate_info.lower_state_info = lower_state_info;
  7307. call_netdevice_notifiers_info(NETDEV_CHANGELOWERSTATE,
  7308. &changelowerstate_info.info);
  7309. }
  7310. EXPORT_SYMBOL(netdev_lower_state_changed);
  7311. static void dev_change_rx_flags(struct net_device *dev, int flags)
  7312. {
  7313. const struct net_device_ops *ops = dev->netdev_ops;
  7314. if (ops->ndo_change_rx_flags)
  7315. ops->ndo_change_rx_flags(dev, flags);
  7316. }
  7317. static int __dev_set_promiscuity(struct net_device *dev, int inc, bool notify)
  7318. {
  7319. unsigned int old_flags = dev->flags;
  7320. unsigned int promiscuity, flags;
  7321. kuid_t uid;
  7322. kgid_t gid;
  7323. ASSERT_RTNL();
  7324. promiscuity = dev->promiscuity + inc;
  7325. if (promiscuity == 0) {
  7326. /*
  7327. * Avoid overflow.
  7328. * If inc causes overflow, untouch promisc and return error.
  7329. */
  7330. if (unlikely(inc > 0)) {
  7331. netdev_warn(dev, "promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n");
  7332. return -EOVERFLOW;
  7333. }
  7334. flags = old_flags & ~IFF_PROMISC;
  7335. } else {
  7336. flags = old_flags | IFF_PROMISC;
  7337. }
  7338. WRITE_ONCE(dev->promiscuity, promiscuity);
  7339. if (flags != old_flags) {
  7340. WRITE_ONCE(dev->flags, flags);
  7341. netdev_info(dev, "%s promiscuous mode\n",
  7342. dev->flags & IFF_PROMISC ? "entered" : "left");
  7343. if (audit_enabled) {
  7344. current_uid_gid(&uid, &gid);
  7345. audit_log(audit_context(), GFP_ATOMIC,
  7346. AUDIT_ANOM_PROMISCUOUS,
  7347. "dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
  7348. dev->name, (dev->flags & IFF_PROMISC),
  7349. (old_flags & IFF_PROMISC),
  7350. from_kuid(&init_user_ns, audit_get_loginuid(current)),
  7351. from_kuid(&init_user_ns, uid),
  7352. from_kgid(&init_user_ns, gid),
  7353. audit_get_sessionid(current));
  7354. }
  7355. dev_change_rx_flags(dev, IFF_PROMISC);
  7356. }
  7357. if (notify)
  7358. __dev_notify_flags(dev, old_flags, IFF_PROMISC, 0, NULL);
  7359. return 0;
  7360. }
  7361. /**
  7362. * dev_set_promiscuity - update promiscuity count on a device
  7363. * @dev: device
  7364. * @inc: modifier
  7365. *
  7366. * Add or remove promiscuity from a device. While the count in the device
  7367. * remains above zero the interface remains promiscuous. Once it hits zero
  7368. * the device reverts back to normal filtering operation. A negative inc
  7369. * value is used to drop promiscuity on the device.
  7370. * Return 0 if successful or a negative errno code on error.
  7371. */
  7372. int dev_set_promiscuity(struct net_device *dev, int inc)
  7373. {
  7374. unsigned int old_flags = dev->flags;
  7375. int err;
  7376. err = __dev_set_promiscuity(dev, inc, true);
  7377. if (err < 0)
  7378. return err;
  7379. if (dev->flags != old_flags)
  7380. dev_set_rx_mode(dev);
  7381. return err;
  7382. }
  7383. EXPORT_SYMBOL(dev_set_promiscuity);
  7384. static int __dev_set_allmulti(struct net_device *dev, int inc, bool notify)
  7385. {
  7386. unsigned int old_flags = dev->flags, old_gflags = dev->gflags;
  7387. unsigned int allmulti, flags;
  7388. ASSERT_RTNL();
  7389. allmulti = dev->allmulti + inc;
  7390. if (allmulti == 0) {
  7391. /*
  7392. * Avoid overflow.
  7393. * If inc causes overflow, untouch allmulti and return error.
  7394. */
  7395. if (unlikely(inc > 0)) {
  7396. netdev_warn(dev, "allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n");
  7397. return -EOVERFLOW;
  7398. }
  7399. flags = old_flags & ~IFF_ALLMULTI;
  7400. } else {
  7401. flags = old_flags | IFF_ALLMULTI;
  7402. }
  7403. WRITE_ONCE(dev->allmulti, allmulti);
  7404. if (flags != old_flags) {
  7405. WRITE_ONCE(dev->flags, flags);
  7406. netdev_info(dev, "%s allmulticast mode\n",
  7407. dev->flags & IFF_ALLMULTI ? "entered" : "left");
  7408. dev_change_rx_flags(dev, IFF_ALLMULTI);
  7409. dev_set_rx_mode(dev);
  7410. if (notify)
  7411. __dev_notify_flags(dev, old_flags,
  7412. dev->gflags ^ old_gflags, 0, NULL);
  7413. }
  7414. return 0;
  7415. }
  7416. /**
  7417. * dev_set_allmulti - update allmulti count on a device
  7418. * @dev: device
  7419. * @inc: modifier
  7420. *
  7421. * Add or remove reception of all multicast frames to a device. While the
  7422. * count in the device remains above zero the interface remains listening
  7423. * to all interfaces. Once it hits zero the device reverts back to normal
  7424. * filtering operation. A negative @inc value is used to drop the counter
  7425. * when releasing a resource needing all multicasts.
  7426. * Return 0 if successful or a negative errno code on error.
  7427. */
  7428. int dev_set_allmulti(struct net_device *dev, int inc)
  7429. {
  7430. return __dev_set_allmulti(dev, inc, true);
  7431. }
  7432. EXPORT_SYMBOL(dev_set_allmulti);
  7433. /*
  7434. * Upload unicast and multicast address lists to device and
  7435. * configure RX filtering. When the device doesn't support unicast
  7436. * filtering it is put in promiscuous mode while unicast addresses
  7437. * are present.
  7438. */
  7439. void __dev_set_rx_mode(struct net_device *dev)
  7440. {
  7441. const struct net_device_ops *ops = dev->netdev_ops;
  7442. /* dev_open will call this function so the list will stay sane. */
  7443. if (!(dev->flags&IFF_UP))
  7444. return;
  7445. if (!netif_device_present(dev))
  7446. return;
  7447. if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
  7448. /* Unicast addresses changes may only happen under the rtnl,
  7449. * therefore calling __dev_set_promiscuity here is safe.
  7450. */
  7451. if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
  7452. __dev_set_promiscuity(dev, 1, false);
  7453. dev->uc_promisc = true;
  7454. } else if (netdev_uc_empty(dev) && dev->uc_promisc) {
  7455. __dev_set_promiscuity(dev, -1, false);
  7456. dev->uc_promisc = false;
  7457. }
  7458. }
  7459. if (ops->ndo_set_rx_mode)
  7460. ops->ndo_set_rx_mode(dev);
  7461. }
  7462. void dev_set_rx_mode(struct net_device *dev)
  7463. {
  7464. netif_addr_lock_bh(dev);
  7465. __dev_set_rx_mode(dev);
  7466. netif_addr_unlock_bh(dev);
  7467. }
  7468. /**
  7469. * dev_get_flags - get flags reported to userspace
  7470. * @dev: device
  7471. *
  7472. * Get the combination of flag bits exported through APIs to userspace.
  7473. */
  7474. unsigned int dev_get_flags(const struct net_device *dev)
  7475. {
  7476. unsigned int flags;
  7477. flags = (READ_ONCE(dev->flags) & ~(IFF_PROMISC |
  7478. IFF_ALLMULTI |
  7479. IFF_RUNNING |
  7480. IFF_LOWER_UP |
  7481. IFF_DORMANT)) |
  7482. (READ_ONCE(dev->gflags) & (IFF_PROMISC |
  7483. IFF_ALLMULTI));
  7484. if (netif_running(dev)) {
  7485. if (netif_oper_up(dev))
  7486. flags |= IFF_RUNNING;
  7487. if (netif_carrier_ok(dev))
  7488. flags |= IFF_LOWER_UP;
  7489. if (netif_dormant(dev))
  7490. flags |= IFF_DORMANT;
  7491. }
  7492. return flags;
  7493. }
  7494. EXPORT_SYMBOL(dev_get_flags);
  7495. int __dev_change_flags(struct net_device *dev, unsigned int flags,
  7496. struct netlink_ext_ack *extack)
  7497. {
  7498. unsigned int old_flags = dev->flags;
  7499. int ret;
  7500. ASSERT_RTNL();
  7501. /*
  7502. * Set the flags on our device.
  7503. */
  7504. dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
  7505. IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
  7506. IFF_AUTOMEDIA)) |
  7507. (dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
  7508. IFF_ALLMULTI));
  7509. /*
  7510. * Load in the correct multicast list now the flags have changed.
  7511. */
  7512. if ((old_flags ^ flags) & IFF_MULTICAST)
  7513. dev_change_rx_flags(dev, IFF_MULTICAST);
  7514. dev_set_rx_mode(dev);
  7515. /*
  7516. * Have we downed the interface. We handle IFF_UP ourselves
  7517. * according to user attempts to set it, rather than blindly
  7518. * setting it.
  7519. */
  7520. ret = 0;
  7521. if ((old_flags ^ flags) & IFF_UP) {
  7522. if (old_flags & IFF_UP)
  7523. __dev_close(dev);
  7524. else
  7525. ret = __dev_open(dev, extack);
  7526. }
  7527. if ((flags ^ dev->gflags) & IFF_PROMISC) {
  7528. int inc = (flags & IFF_PROMISC) ? 1 : -1;
  7529. unsigned int old_flags = dev->flags;
  7530. dev->gflags ^= IFF_PROMISC;
  7531. if (__dev_set_promiscuity(dev, inc, false) >= 0)
  7532. if (dev->flags != old_flags)
  7533. dev_set_rx_mode(dev);
  7534. }
  7535. /* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
  7536. * is important. Some (broken) drivers set IFF_PROMISC, when
  7537. * IFF_ALLMULTI is requested not asking us and not reporting.
  7538. */
  7539. if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
  7540. int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
  7541. dev->gflags ^= IFF_ALLMULTI;
  7542. __dev_set_allmulti(dev, inc, false);
  7543. }
  7544. return ret;
  7545. }
  7546. void __dev_notify_flags(struct net_device *dev, unsigned int old_flags,
  7547. unsigned int gchanges, u32 portid,
  7548. const struct nlmsghdr *nlh)
  7549. {
  7550. unsigned int changes = dev->flags ^ old_flags;
  7551. if (gchanges)
  7552. rtmsg_ifinfo(RTM_NEWLINK, dev, gchanges, GFP_ATOMIC, portid, nlh);
  7553. if (changes & IFF_UP) {
  7554. if (dev->flags & IFF_UP)
  7555. call_netdevice_notifiers(NETDEV_UP, dev);
  7556. else
  7557. call_netdevice_notifiers(NETDEV_DOWN, dev);
  7558. }
  7559. if (dev->flags & IFF_UP &&
  7560. (changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE))) {
  7561. struct netdev_notifier_change_info change_info = {
  7562. .info = {
  7563. .dev = dev,
  7564. },
  7565. .flags_changed = changes,
  7566. };
  7567. call_netdevice_notifiers_info(NETDEV_CHANGE, &change_info.info);
  7568. }
  7569. }
  7570. /**
  7571. * dev_change_flags - change device settings
  7572. * @dev: device
  7573. * @flags: device state flags
  7574. * @extack: netlink extended ack
  7575. *
  7576. * Change settings on device based state flags. The flags are
  7577. * in the userspace exported format.
  7578. */
  7579. int dev_change_flags(struct net_device *dev, unsigned int flags,
  7580. struct netlink_ext_ack *extack)
  7581. {
  7582. int ret;
  7583. unsigned int changes, old_flags = dev->flags, old_gflags = dev->gflags;
  7584. ret = __dev_change_flags(dev, flags, extack);
  7585. if (ret < 0)
  7586. return ret;
  7587. changes = (old_flags ^ dev->flags) | (old_gflags ^ dev->gflags);
  7588. __dev_notify_flags(dev, old_flags, changes, 0, NULL);
  7589. return ret;
  7590. }
  7591. EXPORT_SYMBOL(dev_change_flags);
  7592. int __dev_set_mtu(struct net_device *dev, int new_mtu)
  7593. {
  7594. const struct net_device_ops *ops = dev->netdev_ops;
  7595. if (ops->ndo_change_mtu)
  7596. return ops->ndo_change_mtu(dev, new_mtu);
  7597. /* Pairs with all the lockless reads of dev->mtu in the stack */
  7598. WRITE_ONCE(dev->mtu, new_mtu);
  7599. return 0;
  7600. }
  7601. EXPORT_SYMBOL(__dev_set_mtu);
  7602. int dev_validate_mtu(struct net_device *dev, int new_mtu,
  7603. struct netlink_ext_ack *extack)
  7604. {
  7605. /* MTU must be positive, and in range */
  7606. if (new_mtu < 0 || new_mtu < dev->min_mtu) {
  7607. NL_SET_ERR_MSG(extack, "mtu less than device minimum");
  7608. return -EINVAL;
  7609. }
  7610. if (dev->max_mtu > 0 && new_mtu > dev->max_mtu) {
  7611. NL_SET_ERR_MSG(extack, "mtu greater than device maximum");
  7612. return -EINVAL;
  7613. }
  7614. return 0;
  7615. }
  7616. /**
  7617. * dev_set_mtu_ext - Change maximum transfer unit
  7618. * @dev: device
  7619. * @new_mtu: new transfer unit
  7620. * @extack: netlink extended ack
  7621. *
  7622. * Change the maximum transfer size of the network device.
  7623. */
  7624. int dev_set_mtu_ext(struct net_device *dev, int new_mtu,
  7625. struct netlink_ext_ack *extack)
  7626. {
  7627. int err, orig_mtu;
  7628. if (new_mtu == dev->mtu)
  7629. return 0;
  7630. err = dev_validate_mtu(dev, new_mtu, extack);
  7631. if (err)
  7632. return err;
  7633. if (!netif_device_present(dev))
  7634. return -ENODEV;
  7635. err = call_netdevice_notifiers(NETDEV_PRECHANGEMTU, dev);
  7636. err = notifier_to_errno(err);
  7637. if (err)
  7638. return err;
  7639. orig_mtu = dev->mtu;
  7640. err = __dev_set_mtu(dev, new_mtu);
  7641. if (!err) {
  7642. err = call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
  7643. orig_mtu);
  7644. err = notifier_to_errno(err);
  7645. if (err) {
  7646. /* setting mtu back and notifying everyone again,
  7647. * so that they have a chance to revert changes.
  7648. */
  7649. __dev_set_mtu(dev, orig_mtu);
  7650. call_netdevice_notifiers_mtu(NETDEV_CHANGEMTU, dev,
  7651. new_mtu);
  7652. }
  7653. }
  7654. return err;
  7655. }
  7656. int dev_set_mtu(struct net_device *dev, int new_mtu)
  7657. {
  7658. struct netlink_ext_ack extack;
  7659. int err;
  7660. memset(&extack, 0, sizeof(extack));
  7661. err = dev_set_mtu_ext(dev, new_mtu, &extack);
  7662. if (err && extack._msg)
  7663. net_err_ratelimited("%s: %s\n", dev->name, extack._msg);
  7664. return err;
  7665. }
  7666. EXPORT_SYMBOL(dev_set_mtu);
  7667. /**
  7668. * dev_change_tx_queue_len - Change TX queue length of a netdevice
  7669. * @dev: device
  7670. * @new_len: new tx queue length
  7671. */
  7672. int dev_change_tx_queue_len(struct net_device *dev, unsigned long new_len)
  7673. {
  7674. unsigned int orig_len = dev->tx_queue_len;
  7675. int res;
  7676. if (new_len != (unsigned int)new_len)
  7677. return -ERANGE;
  7678. if (new_len != orig_len) {
  7679. WRITE_ONCE(dev->tx_queue_len, new_len);
  7680. res = call_netdevice_notifiers(NETDEV_CHANGE_TX_QUEUE_LEN, dev);
  7681. res = notifier_to_errno(res);
  7682. if (res)
  7683. goto err_rollback;
  7684. res = dev_qdisc_change_tx_queue_len(dev);
  7685. if (res)
  7686. goto err_rollback;
  7687. }
  7688. return 0;
  7689. err_rollback:
  7690. netdev_err(dev, "refused to change device tx_queue_len\n");
  7691. WRITE_ONCE(dev->tx_queue_len, orig_len);
  7692. return res;
  7693. }
  7694. /**
  7695. * dev_set_group - Change group this device belongs to
  7696. * @dev: device
  7697. * @new_group: group this device should belong to
  7698. */
  7699. void dev_set_group(struct net_device *dev, int new_group)
  7700. {
  7701. dev->group = new_group;
  7702. }
  7703. /**
  7704. * dev_pre_changeaddr_notify - Call NETDEV_PRE_CHANGEADDR.
  7705. * @dev: device
  7706. * @addr: new address
  7707. * @extack: netlink extended ack
  7708. */
  7709. int dev_pre_changeaddr_notify(struct net_device *dev, const char *addr,
  7710. struct netlink_ext_ack *extack)
  7711. {
  7712. struct netdev_notifier_pre_changeaddr_info info = {
  7713. .info.dev = dev,
  7714. .info.extack = extack,
  7715. .dev_addr = addr,
  7716. };
  7717. int rc;
  7718. rc = call_netdevice_notifiers_info(NETDEV_PRE_CHANGEADDR, &info.info);
  7719. return notifier_to_errno(rc);
  7720. }
  7721. EXPORT_SYMBOL(dev_pre_changeaddr_notify);
  7722. /**
  7723. * dev_set_mac_address - Change Media Access Control Address
  7724. * @dev: device
  7725. * @sa: new address
  7726. * @extack: netlink extended ack
  7727. *
  7728. * Change the hardware (MAC) address of the device
  7729. */
  7730. int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa,
  7731. struct netlink_ext_ack *extack)
  7732. {
  7733. const struct net_device_ops *ops = dev->netdev_ops;
  7734. int err;
  7735. if (!ops->ndo_set_mac_address)
  7736. return -EOPNOTSUPP;
  7737. if (sa->sa_family != dev->type)
  7738. return -EINVAL;
  7739. if (!netif_device_present(dev))
  7740. return -ENODEV;
  7741. err = dev_pre_changeaddr_notify(dev, sa->sa_data, extack);
  7742. if (err)
  7743. return err;
  7744. if (memcmp(dev->dev_addr, sa->sa_data, dev->addr_len)) {
  7745. err = ops->ndo_set_mac_address(dev, sa);
  7746. if (err)
  7747. return err;
  7748. }
  7749. dev->addr_assign_type = NET_ADDR_SET;
  7750. call_netdevice_notifiers(NETDEV_CHANGEADDR, dev);
  7751. add_device_randomness(dev->dev_addr, dev->addr_len);
  7752. return 0;
  7753. }
  7754. EXPORT_SYMBOL(dev_set_mac_address);
  7755. DECLARE_RWSEM(dev_addr_sem);
  7756. int dev_set_mac_address_user(struct net_device *dev, struct sockaddr *sa,
  7757. struct netlink_ext_ack *extack)
  7758. {
  7759. int ret;
  7760. down_write(&dev_addr_sem);
  7761. ret = dev_set_mac_address(dev, sa, extack);
  7762. up_write(&dev_addr_sem);
  7763. return ret;
  7764. }
  7765. EXPORT_SYMBOL(dev_set_mac_address_user);
  7766. int dev_get_mac_address(struct sockaddr *sa, struct net *net, char *dev_name)
  7767. {
  7768. size_t size = sizeof(sa->sa_data_min);
  7769. struct net_device *dev;
  7770. int ret = 0;
  7771. down_read(&dev_addr_sem);
  7772. rcu_read_lock();
  7773. dev = dev_get_by_name_rcu(net, dev_name);
  7774. if (!dev) {
  7775. ret = -ENODEV;
  7776. goto unlock;
  7777. }
  7778. if (!dev->addr_len)
  7779. memset(sa->sa_data, 0, size);
  7780. else
  7781. memcpy(sa->sa_data, dev->dev_addr,
  7782. min_t(size_t, size, dev->addr_len));
  7783. sa->sa_family = dev->type;
  7784. unlock:
  7785. rcu_read_unlock();
  7786. up_read(&dev_addr_sem);
  7787. return ret;
  7788. }
  7789. EXPORT_SYMBOL(dev_get_mac_address);
  7790. /**
  7791. * dev_change_carrier - Change device carrier
  7792. * @dev: device
  7793. * @new_carrier: new value
  7794. *
  7795. * Change device carrier
  7796. */
  7797. int dev_change_carrier(struct net_device *dev, bool new_carrier)
  7798. {
  7799. const struct net_device_ops *ops = dev->netdev_ops;
  7800. if (!ops->ndo_change_carrier)
  7801. return -EOPNOTSUPP;
  7802. if (!netif_device_present(dev))
  7803. return -ENODEV;
  7804. return ops->ndo_change_carrier(dev, new_carrier);
  7805. }
  7806. /**
  7807. * dev_get_phys_port_id - Get device physical port ID
  7808. * @dev: device
  7809. * @ppid: port ID
  7810. *
  7811. * Get device physical port ID
  7812. */
  7813. int dev_get_phys_port_id(struct net_device *dev,
  7814. struct netdev_phys_item_id *ppid)
  7815. {
  7816. const struct net_device_ops *ops = dev->netdev_ops;
  7817. if (!ops->ndo_get_phys_port_id)
  7818. return -EOPNOTSUPP;
  7819. return ops->ndo_get_phys_port_id(dev, ppid);
  7820. }
  7821. /**
  7822. * dev_get_phys_port_name - Get device physical port name
  7823. * @dev: device
  7824. * @name: port name
  7825. * @len: limit of bytes to copy to name
  7826. *
  7827. * Get device physical port name
  7828. */
  7829. int dev_get_phys_port_name(struct net_device *dev,
  7830. char *name, size_t len)
  7831. {
  7832. const struct net_device_ops *ops = dev->netdev_ops;
  7833. int err;
  7834. if (ops->ndo_get_phys_port_name) {
  7835. err = ops->ndo_get_phys_port_name(dev, name, len);
  7836. if (err != -EOPNOTSUPP)
  7837. return err;
  7838. }
  7839. return devlink_compat_phys_port_name_get(dev, name, len);
  7840. }
  7841. /**
  7842. * dev_get_port_parent_id - Get the device's port parent identifier
  7843. * @dev: network device
  7844. * @ppid: pointer to a storage for the port's parent identifier
  7845. * @recurse: allow/disallow recursion to lower devices
  7846. *
  7847. * Get the devices's port parent identifier
  7848. */
  7849. int dev_get_port_parent_id(struct net_device *dev,
  7850. struct netdev_phys_item_id *ppid,
  7851. bool recurse)
  7852. {
  7853. const struct net_device_ops *ops = dev->netdev_ops;
  7854. struct netdev_phys_item_id first = { };
  7855. struct net_device *lower_dev;
  7856. struct list_head *iter;
  7857. int err;
  7858. if (ops->ndo_get_port_parent_id) {
  7859. err = ops->ndo_get_port_parent_id(dev, ppid);
  7860. if (err != -EOPNOTSUPP)
  7861. return err;
  7862. }
  7863. err = devlink_compat_switch_id_get(dev, ppid);
  7864. if (!recurse || err != -EOPNOTSUPP)
  7865. return err;
  7866. netdev_for_each_lower_dev(dev, lower_dev, iter) {
  7867. err = dev_get_port_parent_id(lower_dev, ppid, true);
  7868. if (err)
  7869. break;
  7870. if (!first.id_len)
  7871. first = *ppid;
  7872. else if (memcmp(&first, ppid, sizeof(*ppid)))
  7873. return -EOPNOTSUPP;
  7874. }
  7875. return err;
  7876. }
  7877. EXPORT_SYMBOL(dev_get_port_parent_id);
  7878. /**
  7879. * netdev_port_same_parent_id - Indicate if two network devices have
  7880. * the same port parent identifier
  7881. * @a: first network device
  7882. * @b: second network device
  7883. */
  7884. bool netdev_port_same_parent_id(struct net_device *a, struct net_device *b)
  7885. {
  7886. struct netdev_phys_item_id a_id = { };
  7887. struct netdev_phys_item_id b_id = { };
  7888. if (dev_get_port_parent_id(a, &a_id, true) ||
  7889. dev_get_port_parent_id(b, &b_id, true))
  7890. return false;
  7891. return netdev_phys_item_id_same(&a_id, &b_id);
  7892. }
  7893. EXPORT_SYMBOL(netdev_port_same_parent_id);
  7894. /**
  7895. * dev_change_proto_down - set carrier according to proto_down.
  7896. *
  7897. * @dev: device
  7898. * @proto_down: new value
  7899. */
  7900. int dev_change_proto_down(struct net_device *dev, bool proto_down)
  7901. {
  7902. if (!dev->change_proto_down)
  7903. return -EOPNOTSUPP;
  7904. if (!netif_device_present(dev))
  7905. return -ENODEV;
  7906. if (proto_down)
  7907. netif_carrier_off(dev);
  7908. else
  7909. netif_carrier_on(dev);
  7910. WRITE_ONCE(dev->proto_down, proto_down);
  7911. return 0;
  7912. }
  7913. /**
  7914. * dev_change_proto_down_reason - proto down reason
  7915. *
  7916. * @dev: device
  7917. * @mask: proto down mask
  7918. * @value: proto down value
  7919. */
  7920. void dev_change_proto_down_reason(struct net_device *dev, unsigned long mask,
  7921. u32 value)
  7922. {
  7923. u32 proto_down_reason;
  7924. int b;
  7925. if (!mask) {
  7926. proto_down_reason = value;
  7927. } else {
  7928. proto_down_reason = dev->proto_down_reason;
  7929. for_each_set_bit(b, &mask, 32) {
  7930. if (value & (1 << b))
  7931. proto_down_reason |= BIT(b);
  7932. else
  7933. proto_down_reason &= ~BIT(b);
  7934. }
  7935. }
  7936. WRITE_ONCE(dev->proto_down_reason, proto_down_reason);
  7937. }
  7938. struct bpf_xdp_link {
  7939. struct bpf_link link;
  7940. struct net_device *dev; /* protected by rtnl_lock, no refcnt held */
  7941. int flags;
  7942. };
  7943. static enum bpf_xdp_mode dev_xdp_mode(struct net_device *dev, u32 flags)
  7944. {
  7945. if (flags & XDP_FLAGS_HW_MODE)
  7946. return XDP_MODE_HW;
  7947. if (flags & XDP_FLAGS_DRV_MODE)
  7948. return XDP_MODE_DRV;
  7949. if (flags & XDP_FLAGS_SKB_MODE)
  7950. return XDP_MODE_SKB;
  7951. return dev->netdev_ops->ndo_bpf ? XDP_MODE_DRV : XDP_MODE_SKB;
  7952. }
  7953. static bpf_op_t dev_xdp_bpf_op(struct net_device *dev, enum bpf_xdp_mode mode)
  7954. {
  7955. switch (mode) {
  7956. case XDP_MODE_SKB:
  7957. return generic_xdp_install;
  7958. case XDP_MODE_DRV:
  7959. case XDP_MODE_HW:
  7960. return dev->netdev_ops->ndo_bpf;
  7961. default:
  7962. return NULL;
  7963. }
  7964. }
  7965. static struct bpf_xdp_link *dev_xdp_link(struct net_device *dev,
  7966. enum bpf_xdp_mode mode)
  7967. {
  7968. return dev->xdp_state[mode].link;
  7969. }
  7970. static struct bpf_prog *dev_xdp_prog(struct net_device *dev,
  7971. enum bpf_xdp_mode mode)
  7972. {
  7973. struct bpf_xdp_link *link = dev_xdp_link(dev, mode);
  7974. if (link)
  7975. return link->link.prog;
  7976. return dev->xdp_state[mode].prog;
  7977. }
  7978. u8 dev_xdp_prog_count(struct net_device *dev)
  7979. {
  7980. u8 count = 0;
  7981. int i;
  7982. for (i = 0; i < __MAX_XDP_MODE; i++)
  7983. if (dev->xdp_state[i].prog || dev->xdp_state[i].link)
  7984. count++;
  7985. return count;
  7986. }
  7987. EXPORT_SYMBOL_GPL(dev_xdp_prog_count);
  7988. int dev_xdp_propagate(struct net_device *dev, struct netdev_bpf *bpf)
  7989. {
  7990. if (!dev->netdev_ops->ndo_bpf)
  7991. return -EOPNOTSUPP;
  7992. if (dev_get_min_mp_channel_count(dev)) {
  7993. NL_SET_ERR_MSG(bpf->extack, "unable to propagate XDP to device using memory provider");
  7994. return -EBUSY;
  7995. }
  7996. return dev->netdev_ops->ndo_bpf(dev, bpf);
  7997. }
  7998. EXPORT_SYMBOL_GPL(dev_xdp_propagate);
  7999. u32 dev_xdp_prog_id(struct net_device *dev, enum bpf_xdp_mode mode)
  8000. {
  8001. struct bpf_prog *prog = dev_xdp_prog(dev, mode);
  8002. return prog ? prog->aux->id : 0;
  8003. }
  8004. static void dev_xdp_set_link(struct net_device *dev, enum bpf_xdp_mode mode,
  8005. struct bpf_xdp_link *link)
  8006. {
  8007. dev->xdp_state[mode].link = link;
  8008. dev->xdp_state[mode].prog = NULL;
  8009. }
  8010. static void dev_xdp_set_prog(struct net_device *dev, enum bpf_xdp_mode mode,
  8011. struct bpf_prog *prog)
  8012. {
  8013. dev->xdp_state[mode].link = NULL;
  8014. dev->xdp_state[mode].prog = prog;
  8015. }
  8016. static int dev_xdp_install(struct net_device *dev, enum bpf_xdp_mode mode,
  8017. bpf_op_t bpf_op, struct netlink_ext_ack *extack,
  8018. u32 flags, struct bpf_prog *prog)
  8019. {
  8020. struct netdev_bpf xdp;
  8021. int err;
  8022. if (dev_get_min_mp_channel_count(dev)) {
  8023. NL_SET_ERR_MSG(extack, "unable to install XDP to device using memory provider");
  8024. return -EBUSY;
  8025. }
  8026. memset(&xdp, 0, sizeof(xdp));
  8027. xdp.command = mode == XDP_MODE_HW ? XDP_SETUP_PROG_HW : XDP_SETUP_PROG;
  8028. xdp.extack = extack;
  8029. xdp.flags = flags;
  8030. xdp.prog = prog;
  8031. /* Drivers assume refcnt is already incremented (i.e, prog pointer is
  8032. * "moved" into driver), so they don't increment it on their own, but
  8033. * they do decrement refcnt when program is detached or replaced.
  8034. * Given net_device also owns link/prog, we need to bump refcnt here
  8035. * to prevent drivers from underflowing it.
  8036. */
  8037. if (prog)
  8038. bpf_prog_inc(prog);
  8039. err = bpf_op(dev, &xdp);
  8040. if (err) {
  8041. if (prog)
  8042. bpf_prog_put(prog);
  8043. return err;
  8044. }
  8045. if (mode != XDP_MODE_HW)
  8046. bpf_prog_change_xdp(dev_xdp_prog(dev, mode), prog);
  8047. return 0;
  8048. }
  8049. static void dev_xdp_uninstall(struct net_device *dev)
  8050. {
  8051. struct bpf_xdp_link *link;
  8052. struct bpf_prog *prog;
  8053. enum bpf_xdp_mode mode;
  8054. bpf_op_t bpf_op;
  8055. ASSERT_RTNL();
  8056. for (mode = XDP_MODE_SKB; mode < __MAX_XDP_MODE; mode++) {
  8057. prog = dev_xdp_prog(dev, mode);
  8058. if (!prog)
  8059. continue;
  8060. bpf_op = dev_xdp_bpf_op(dev, mode);
  8061. if (!bpf_op)
  8062. continue;
  8063. WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
  8064. /* auto-detach link from net device */
  8065. link = dev_xdp_link(dev, mode);
  8066. if (link)
  8067. link->dev = NULL;
  8068. else
  8069. bpf_prog_put(prog);
  8070. dev_xdp_set_link(dev, mode, NULL);
  8071. }
  8072. }
  8073. static int dev_xdp_attach(struct net_device *dev, struct netlink_ext_ack *extack,
  8074. struct bpf_xdp_link *link, struct bpf_prog *new_prog,
  8075. struct bpf_prog *old_prog, u32 flags)
  8076. {
  8077. unsigned int num_modes = hweight32(flags & XDP_FLAGS_MODES);
  8078. struct bpf_prog *cur_prog;
  8079. struct net_device *upper;
  8080. struct list_head *iter;
  8081. enum bpf_xdp_mode mode;
  8082. bpf_op_t bpf_op;
  8083. int err;
  8084. ASSERT_RTNL();
  8085. /* either link or prog attachment, never both */
  8086. if (link && (new_prog || old_prog))
  8087. return -EINVAL;
  8088. /* link supports only XDP mode flags */
  8089. if (link && (flags & ~XDP_FLAGS_MODES)) {
  8090. NL_SET_ERR_MSG(extack, "Invalid XDP flags for BPF link attachment");
  8091. return -EINVAL;
  8092. }
  8093. /* just one XDP mode bit should be set, zero defaults to drv/skb mode */
  8094. if (num_modes > 1) {
  8095. NL_SET_ERR_MSG(extack, "Only one XDP mode flag can be set");
  8096. return -EINVAL;
  8097. }
  8098. /* avoid ambiguity if offload + drv/skb mode progs are both loaded */
  8099. if (!num_modes && dev_xdp_prog_count(dev) > 1) {
  8100. NL_SET_ERR_MSG(extack,
  8101. "More than one program loaded, unset mode is ambiguous");
  8102. return -EINVAL;
  8103. }
  8104. /* old_prog != NULL implies XDP_FLAGS_REPLACE is set */
  8105. if (old_prog && !(flags & XDP_FLAGS_REPLACE)) {
  8106. NL_SET_ERR_MSG(extack, "XDP_FLAGS_REPLACE is not specified");
  8107. return -EINVAL;
  8108. }
  8109. mode = dev_xdp_mode(dev, flags);
  8110. /* can't replace attached link */
  8111. if (dev_xdp_link(dev, mode)) {
  8112. NL_SET_ERR_MSG(extack, "Can't replace active BPF XDP link");
  8113. return -EBUSY;
  8114. }
  8115. /* don't allow if an upper device already has a program */
  8116. netdev_for_each_upper_dev_rcu(dev, upper, iter) {
  8117. if (dev_xdp_prog_count(upper) > 0) {
  8118. NL_SET_ERR_MSG(extack, "Cannot attach when an upper device already has a program");
  8119. return -EEXIST;
  8120. }
  8121. }
  8122. cur_prog = dev_xdp_prog(dev, mode);
  8123. /* can't replace attached prog with link */
  8124. if (link && cur_prog) {
  8125. NL_SET_ERR_MSG(extack, "Can't replace active XDP program with BPF link");
  8126. return -EBUSY;
  8127. }
  8128. if ((flags & XDP_FLAGS_REPLACE) && cur_prog != old_prog) {
  8129. NL_SET_ERR_MSG(extack, "Active program does not match expected");
  8130. return -EEXIST;
  8131. }
  8132. /* put effective new program into new_prog */
  8133. if (link)
  8134. new_prog = link->link.prog;
  8135. if (new_prog) {
  8136. bool offload = mode == XDP_MODE_HW;
  8137. enum bpf_xdp_mode other_mode = mode == XDP_MODE_SKB
  8138. ? XDP_MODE_DRV : XDP_MODE_SKB;
  8139. if ((flags & XDP_FLAGS_UPDATE_IF_NOEXIST) && cur_prog) {
  8140. NL_SET_ERR_MSG(extack, "XDP program already attached");
  8141. return -EBUSY;
  8142. }
  8143. if (!offload && dev_xdp_prog(dev, other_mode)) {
  8144. NL_SET_ERR_MSG(extack, "Native and generic XDP can't be active at the same time");
  8145. return -EEXIST;
  8146. }
  8147. if (!offload && bpf_prog_is_offloaded(new_prog->aux)) {
  8148. NL_SET_ERR_MSG(extack, "Using offloaded program without HW_MODE flag is not supported");
  8149. return -EINVAL;
  8150. }
  8151. if (bpf_prog_is_dev_bound(new_prog->aux) && !bpf_offload_dev_match(new_prog, dev)) {
  8152. NL_SET_ERR_MSG(extack, "Program bound to different device");
  8153. return -EINVAL;
  8154. }
  8155. if (bpf_prog_is_dev_bound(new_prog->aux) && mode == XDP_MODE_SKB) {
  8156. NL_SET_ERR_MSG(extack, "Can't attach device-bound programs in generic mode");
  8157. return -EINVAL;
  8158. }
  8159. if (new_prog->expected_attach_type == BPF_XDP_DEVMAP) {
  8160. NL_SET_ERR_MSG(extack, "BPF_XDP_DEVMAP programs can not be attached to a device");
  8161. return -EINVAL;
  8162. }
  8163. if (new_prog->expected_attach_type == BPF_XDP_CPUMAP) {
  8164. NL_SET_ERR_MSG(extack, "BPF_XDP_CPUMAP programs can not be attached to a device");
  8165. return -EINVAL;
  8166. }
  8167. }
  8168. /* don't call drivers if the effective program didn't change */
  8169. if (new_prog != cur_prog) {
  8170. bpf_op = dev_xdp_bpf_op(dev, mode);
  8171. if (!bpf_op) {
  8172. NL_SET_ERR_MSG(extack, "Underlying driver does not support XDP in native mode");
  8173. return -EOPNOTSUPP;
  8174. }
  8175. err = dev_xdp_install(dev, mode, bpf_op, extack, flags, new_prog);
  8176. if (err)
  8177. return err;
  8178. }
  8179. if (link)
  8180. dev_xdp_set_link(dev, mode, link);
  8181. else
  8182. dev_xdp_set_prog(dev, mode, new_prog);
  8183. if (cur_prog)
  8184. bpf_prog_put(cur_prog);
  8185. return 0;
  8186. }
  8187. static int dev_xdp_attach_link(struct net_device *dev,
  8188. struct netlink_ext_ack *extack,
  8189. struct bpf_xdp_link *link)
  8190. {
  8191. return dev_xdp_attach(dev, extack, link, NULL, NULL, link->flags);
  8192. }
  8193. static int dev_xdp_detach_link(struct net_device *dev,
  8194. struct netlink_ext_ack *extack,
  8195. struct bpf_xdp_link *link)
  8196. {
  8197. enum bpf_xdp_mode mode;
  8198. bpf_op_t bpf_op;
  8199. ASSERT_RTNL();
  8200. mode = dev_xdp_mode(dev, link->flags);
  8201. if (dev_xdp_link(dev, mode) != link)
  8202. return -EINVAL;
  8203. bpf_op = dev_xdp_bpf_op(dev, mode);
  8204. WARN_ON(dev_xdp_install(dev, mode, bpf_op, NULL, 0, NULL));
  8205. dev_xdp_set_link(dev, mode, NULL);
  8206. return 0;
  8207. }
  8208. static void bpf_xdp_link_release(struct bpf_link *link)
  8209. {
  8210. struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
  8211. rtnl_lock();
  8212. /* if racing with net_device's tear down, xdp_link->dev might be
  8213. * already NULL, in which case link was already auto-detached
  8214. */
  8215. if (xdp_link->dev) {
  8216. WARN_ON(dev_xdp_detach_link(xdp_link->dev, NULL, xdp_link));
  8217. xdp_link->dev = NULL;
  8218. }
  8219. rtnl_unlock();
  8220. }
  8221. static int bpf_xdp_link_detach(struct bpf_link *link)
  8222. {
  8223. bpf_xdp_link_release(link);
  8224. return 0;
  8225. }
  8226. static void bpf_xdp_link_dealloc(struct bpf_link *link)
  8227. {
  8228. struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
  8229. kfree(xdp_link);
  8230. }
  8231. static void bpf_xdp_link_show_fdinfo(const struct bpf_link *link,
  8232. struct seq_file *seq)
  8233. {
  8234. struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
  8235. u32 ifindex = 0;
  8236. rtnl_lock();
  8237. if (xdp_link->dev)
  8238. ifindex = xdp_link->dev->ifindex;
  8239. rtnl_unlock();
  8240. seq_printf(seq, "ifindex:\t%u\n", ifindex);
  8241. }
  8242. static int bpf_xdp_link_fill_link_info(const struct bpf_link *link,
  8243. struct bpf_link_info *info)
  8244. {
  8245. struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
  8246. u32 ifindex = 0;
  8247. rtnl_lock();
  8248. if (xdp_link->dev)
  8249. ifindex = xdp_link->dev->ifindex;
  8250. rtnl_unlock();
  8251. info->xdp.ifindex = ifindex;
  8252. return 0;
  8253. }
  8254. static int bpf_xdp_link_update(struct bpf_link *link, struct bpf_prog *new_prog,
  8255. struct bpf_prog *old_prog)
  8256. {
  8257. struct bpf_xdp_link *xdp_link = container_of(link, struct bpf_xdp_link, link);
  8258. enum bpf_xdp_mode mode;
  8259. bpf_op_t bpf_op;
  8260. int err = 0;
  8261. rtnl_lock();
  8262. /* link might have been auto-released already, so fail */
  8263. if (!xdp_link->dev) {
  8264. err = -ENOLINK;
  8265. goto out_unlock;
  8266. }
  8267. if (old_prog && link->prog != old_prog) {
  8268. err = -EPERM;
  8269. goto out_unlock;
  8270. }
  8271. old_prog = link->prog;
  8272. if (old_prog->type != new_prog->type ||
  8273. old_prog->expected_attach_type != new_prog->expected_attach_type) {
  8274. err = -EINVAL;
  8275. goto out_unlock;
  8276. }
  8277. if (old_prog == new_prog) {
  8278. /* no-op, don't disturb drivers */
  8279. bpf_prog_put(new_prog);
  8280. goto out_unlock;
  8281. }
  8282. mode = dev_xdp_mode(xdp_link->dev, xdp_link->flags);
  8283. bpf_op = dev_xdp_bpf_op(xdp_link->dev, mode);
  8284. err = dev_xdp_install(xdp_link->dev, mode, bpf_op, NULL,
  8285. xdp_link->flags, new_prog);
  8286. if (err)
  8287. goto out_unlock;
  8288. old_prog = xchg(&link->prog, new_prog);
  8289. bpf_prog_put(old_prog);
  8290. out_unlock:
  8291. rtnl_unlock();
  8292. return err;
  8293. }
  8294. static const struct bpf_link_ops bpf_xdp_link_lops = {
  8295. .release = bpf_xdp_link_release,
  8296. .dealloc = bpf_xdp_link_dealloc,
  8297. .detach = bpf_xdp_link_detach,
  8298. .show_fdinfo = bpf_xdp_link_show_fdinfo,
  8299. .fill_link_info = bpf_xdp_link_fill_link_info,
  8300. .update_prog = bpf_xdp_link_update,
  8301. };
  8302. int bpf_xdp_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
  8303. {
  8304. struct net *net = current->nsproxy->net_ns;
  8305. struct bpf_link_primer link_primer;
  8306. struct netlink_ext_ack extack = {};
  8307. struct bpf_xdp_link *link;
  8308. struct net_device *dev;
  8309. int err, fd;
  8310. rtnl_lock();
  8311. dev = dev_get_by_index(net, attr->link_create.target_ifindex);
  8312. if (!dev) {
  8313. rtnl_unlock();
  8314. return -EINVAL;
  8315. }
  8316. link = kzalloc(sizeof(*link), GFP_USER);
  8317. if (!link) {
  8318. err = -ENOMEM;
  8319. goto unlock;
  8320. }
  8321. bpf_link_init(&link->link, BPF_LINK_TYPE_XDP, &bpf_xdp_link_lops, prog);
  8322. link->dev = dev;
  8323. link->flags = attr->link_create.flags;
  8324. err = bpf_link_prime(&link->link, &link_primer);
  8325. if (err) {
  8326. kfree(link);
  8327. goto unlock;
  8328. }
  8329. err = dev_xdp_attach_link(dev, &extack, link);
  8330. rtnl_unlock();
  8331. if (err) {
  8332. link->dev = NULL;
  8333. bpf_link_cleanup(&link_primer);
  8334. trace_bpf_xdp_link_attach_failed(extack._msg);
  8335. goto out_put_dev;
  8336. }
  8337. fd = bpf_link_settle(&link_primer);
  8338. /* link itself doesn't hold dev's refcnt to not complicate shutdown */
  8339. dev_put(dev);
  8340. return fd;
  8341. unlock:
  8342. rtnl_unlock();
  8343. out_put_dev:
  8344. dev_put(dev);
  8345. return err;
  8346. }
  8347. /**
  8348. * dev_change_xdp_fd - set or clear a bpf program for a device rx path
  8349. * @dev: device
  8350. * @extack: netlink extended ack
  8351. * @fd: new program fd or negative value to clear
  8352. * @expected_fd: old program fd that userspace expects to replace or clear
  8353. * @flags: xdp-related flags
  8354. *
  8355. * Set or clear a bpf program for a device
  8356. */
  8357. int dev_change_xdp_fd(struct net_device *dev, struct netlink_ext_ack *extack,
  8358. int fd, int expected_fd, u32 flags)
  8359. {
  8360. enum bpf_xdp_mode mode = dev_xdp_mode(dev, flags);
  8361. struct bpf_prog *new_prog = NULL, *old_prog = NULL;
  8362. int err;
  8363. ASSERT_RTNL();
  8364. if (fd >= 0) {
  8365. new_prog = bpf_prog_get_type_dev(fd, BPF_PROG_TYPE_XDP,
  8366. mode != XDP_MODE_SKB);
  8367. if (IS_ERR(new_prog))
  8368. return PTR_ERR(new_prog);
  8369. }
  8370. if (expected_fd >= 0) {
  8371. old_prog = bpf_prog_get_type_dev(expected_fd, BPF_PROG_TYPE_XDP,
  8372. mode != XDP_MODE_SKB);
  8373. if (IS_ERR(old_prog)) {
  8374. err = PTR_ERR(old_prog);
  8375. old_prog = NULL;
  8376. goto err_out;
  8377. }
  8378. }
  8379. err = dev_xdp_attach(dev, extack, NULL, new_prog, old_prog, flags);
  8380. err_out:
  8381. if (err && new_prog)
  8382. bpf_prog_put(new_prog);
  8383. if (old_prog)
  8384. bpf_prog_put(old_prog);
  8385. return err;
  8386. }
  8387. u32 dev_get_min_mp_channel_count(const struct net_device *dev)
  8388. {
  8389. int i;
  8390. ASSERT_RTNL();
  8391. for (i = dev->real_num_rx_queues - 1; i >= 0; i--)
  8392. if (dev->_rx[i].mp_params.mp_priv)
  8393. /* The channel count is the idx plus 1. */
  8394. return i + 1;
  8395. return 0;
  8396. }
  8397. /**
  8398. * dev_index_reserve() - allocate an ifindex in a namespace
  8399. * @net: the applicable net namespace
  8400. * @ifindex: requested ifindex, pass %0 to get one allocated
  8401. *
  8402. * Allocate a ifindex for a new device. Caller must either use the ifindex
  8403. * to store the device (via list_netdevice()) or call dev_index_release()
  8404. * to give the index up.
  8405. *
  8406. * Return: a suitable unique value for a new device interface number or -errno.
  8407. */
  8408. static int dev_index_reserve(struct net *net, u32 ifindex)
  8409. {
  8410. int err;
  8411. if (ifindex > INT_MAX) {
  8412. DEBUG_NET_WARN_ON_ONCE(1);
  8413. return -EINVAL;
  8414. }
  8415. if (!ifindex)
  8416. err = xa_alloc_cyclic(&net->dev_by_index, &ifindex, NULL,
  8417. xa_limit_31b, &net->ifindex, GFP_KERNEL);
  8418. else
  8419. err = xa_insert(&net->dev_by_index, ifindex, NULL, GFP_KERNEL);
  8420. if (err < 0)
  8421. return err;
  8422. return ifindex;
  8423. }
  8424. static void dev_index_release(struct net *net, int ifindex)
  8425. {
  8426. /* Expect only unused indexes, unlist_netdevice() removes the used */
  8427. WARN_ON(xa_erase(&net->dev_by_index, ifindex));
  8428. }
  8429. /* Delayed registration/unregisteration */
  8430. LIST_HEAD(net_todo_list);
  8431. DECLARE_WAIT_QUEUE_HEAD(netdev_unregistering_wq);
  8432. atomic_t dev_unreg_count = ATOMIC_INIT(0);
  8433. static void net_set_todo(struct net_device *dev)
  8434. {
  8435. list_add_tail(&dev->todo_list, &net_todo_list);
  8436. }
  8437. static netdev_features_t netdev_sync_upper_features(struct net_device *lower,
  8438. struct net_device *upper, netdev_features_t features)
  8439. {
  8440. netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
  8441. netdev_features_t feature;
  8442. int feature_bit;
  8443. for_each_netdev_feature(upper_disables, feature_bit) {
  8444. feature = __NETIF_F_BIT(feature_bit);
  8445. if (!(upper->wanted_features & feature)
  8446. && (features & feature)) {
  8447. netdev_dbg(lower, "Dropping feature %pNF, upper dev %s has it off.\n",
  8448. &feature, upper->name);
  8449. features &= ~feature;
  8450. }
  8451. }
  8452. return features;
  8453. }
  8454. static void netdev_sync_lower_features(struct net_device *upper,
  8455. struct net_device *lower, netdev_features_t features)
  8456. {
  8457. netdev_features_t upper_disables = NETIF_F_UPPER_DISABLES;
  8458. netdev_features_t feature;
  8459. int feature_bit;
  8460. for_each_netdev_feature(upper_disables, feature_bit) {
  8461. feature = __NETIF_F_BIT(feature_bit);
  8462. if (!(features & feature) && (lower->features & feature)) {
  8463. netdev_dbg(upper, "Disabling feature %pNF on lower dev %s.\n",
  8464. &feature, lower->name);
  8465. lower->wanted_features &= ~feature;
  8466. __netdev_update_features(lower);
  8467. if (unlikely(lower->features & feature))
  8468. netdev_WARN(upper, "failed to disable %pNF on %s!\n",
  8469. &feature, lower->name);
  8470. else
  8471. netdev_features_change(lower);
  8472. }
  8473. }
  8474. }
  8475. static bool netdev_has_ip_or_hw_csum(netdev_features_t features)
  8476. {
  8477. netdev_features_t ip_csum_mask = NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
  8478. bool ip_csum = (features & ip_csum_mask) == ip_csum_mask;
  8479. bool hw_csum = features & NETIF_F_HW_CSUM;
  8480. return ip_csum || hw_csum;
  8481. }
  8482. static netdev_features_t netdev_fix_features(struct net_device *dev,
  8483. netdev_features_t features)
  8484. {
  8485. /* Fix illegal checksum combinations */
  8486. if ((features & NETIF_F_HW_CSUM) &&
  8487. (features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
  8488. netdev_warn(dev, "mixed HW and IP checksum settings.\n");
  8489. features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
  8490. }
  8491. /* TSO requires that SG is present as well. */
  8492. if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
  8493. netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
  8494. features &= ~NETIF_F_ALL_TSO;
  8495. }
  8496. if ((features & NETIF_F_TSO) && !(features & NETIF_F_HW_CSUM) &&
  8497. !(features & NETIF_F_IP_CSUM)) {
  8498. netdev_dbg(dev, "Dropping TSO features since no CSUM feature.\n");
  8499. features &= ~NETIF_F_TSO;
  8500. features &= ~NETIF_F_TSO_ECN;
  8501. }
  8502. if ((features & NETIF_F_TSO6) && !(features & NETIF_F_HW_CSUM) &&
  8503. !(features & NETIF_F_IPV6_CSUM)) {
  8504. netdev_dbg(dev, "Dropping TSO6 features since no CSUM feature.\n");
  8505. features &= ~NETIF_F_TSO6;
  8506. }
  8507. /* TSO with IPv4 ID mangling requires IPv4 TSO be enabled */
  8508. if ((features & NETIF_F_TSO_MANGLEID) && !(features & NETIF_F_TSO))
  8509. features &= ~NETIF_F_TSO_MANGLEID;
  8510. /* TSO ECN requires that TSO is present as well. */
  8511. if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
  8512. features &= ~NETIF_F_TSO_ECN;
  8513. /* Software GSO depends on SG. */
  8514. if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
  8515. netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
  8516. features &= ~NETIF_F_GSO;
  8517. }
  8518. /* GSO partial features require GSO partial be set */
  8519. if ((features & dev->gso_partial_features) &&
  8520. !(features & NETIF_F_GSO_PARTIAL)) {
  8521. netdev_dbg(dev,
  8522. "Dropping partially supported GSO features since no GSO partial.\n");
  8523. features &= ~dev->gso_partial_features;
  8524. }
  8525. if (!(features & NETIF_F_RXCSUM)) {
  8526. /* NETIF_F_GRO_HW implies doing RXCSUM since every packet
  8527. * successfully merged by hardware must also have the
  8528. * checksum verified by hardware. If the user does not
  8529. * want to enable RXCSUM, logically, we should disable GRO_HW.
  8530. */
  8531. if (features & NETIF_F_GRO_HW) {
  8532. netdev_dbg(dev, "Dropping NETIF_F_GRO_HW since no RXCSUM feature.\n");
  8533. features &= ~NETIF_F_GRO_HW;
  8534. }
  8535. }
  8536. /* LRO/HW-GRO features cannot be combined with RX-FCS */
  8537. if (features & NETIF_F_RXFCS) {
  8538. if (features & NETIF_F_LRO) {
  8539. netdev_dbg(dev, "Dropping LRO feature since RX-FCS is requested.\n");
  8540. features &= ~NETIF_F_LRO;
  8541. }
  8542. if (features & NETIF_F_GRO_HW) {
  8543. netdev_dbg(dev, "Dropping HW-GRO feature since RX-FCS is requested.\n");
  8544. features &= ~NETIF_F_GRO_HW;
  8545. }
  8546. }
  8547. if ((features & NETIF_F_GRO_HW) && (features & NETIF_F_LRO)) {
  8548. netdev_dbg(dev, "Dropping LRO feature since HW-GRO is requested.\n");
  8549. features &= ~NETIF_F_LRO;
  8550. }
  8551. if ((features & NETIF_F_HW_TLS_TX) && !netdev_has_ip_or_hw_csum(features)) {
  8552. netdev_dbg(dev, "Dropping TLS TX HW offload feature since no CSUM feature.\n");
  8553. features &= ~NETIF_F_HW_TLS_TX;
  8554. }
  8555. if ((features & NETIF_F_HW_TLS_RX) && !(features & NETIF_F_RXCSUM)) {
  8556. netdev_dbg(dev, "Dropping TLS RX HW offload feature since no RXCSUM feature.\n");
  8557. features &= ~NETIF_F_HW_TLS_RX;
  8558. }
  8559. if ((features & NETIF_F_GSO_UDP_L4) && !netdev_has_ip_or_hw_csum(features)) {
  8560. netdev_dbg(dev, "Dropping USO feature since no CSUM feature.\n");
  8561. features &= ~NETIF_F_GSO_UDP_L4;
  8562. }
  8563. return features;
  8564. }
  8565. int __netdev_update_features(struct net_device *dev)
  8566. {
  8567. struct net_device *upper, *lower;
  8568. netdev_features_t features;
  8569. struct list_head *iter;
  8570. int err = -1;
  8571. ASSERT_RTNL();
  8572. features = netdev_get_wanted_features(dev);
  8573. if (dev->netdev_ops->ndo_fix_features)
  8574. features = dev->netdev_ops->ndo_fix_features(dev, features);
  8575. /* driver might be less strict about feature dependencies */
  8576. features = netdev_fix_features(dev, features);
  8577. /* some features can't be enabled if they're off on an upper device */
  8578. netdev_for_each_upper_dev_rcu(dev, upper, iter)
  8579. features = netdev_sync_upper_features(dev, upper, features);
  8580. if (dev->features == features)
  8581. goto sync_lower;
  8582. netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
  8583. &dev->features, &features);
  8584. if (dev->netdev_ops->ndo_set_features)
  8585. err = dev->netdev_ops->ndo_set_features(dev, features);
  8586. else
  8587. err = 0;
  8588. if (unlikely(err < 0)) {
  8589. netdev_err(dev,
  8590. "set_features() failed (%d); wanted %pNF, left %pNF\n",
  8591. err, &features, &dev->features);
  8592. /* return non-0 since some features might have changed and
  8593. * it's better to fire a spurious notification than miss it
  8594. */
  8595. return -1;
  8596. }
  8597. sync_lower:
  8598. /* some features must be disabled on lower devices when disabled
  8599. * on an upper device (think: bonding master or bridge)
  8600. */
  8601. netdev_for_each_lower_dev(dev, lower, iter)
  8602. netdev_sync_lower_features(dev, lower, features);
  8603. if (!err) {
  8604. netdev_features_t diff = features ^ dev->features;
  8605. if (diff & NETIF_F_RX_UDP_TUNNEL_PORT) {
  8606. /* udp_tunnel_{get,drop}_rx_info both need
  8607. * NETIF_F_RX_UDP_TUNNEL_PORT enabled on the
  8608. * device, or they won't do anything.
  8609. * Thus we need to update dev->features
  8610. * *before* calling udp_tunnel_get_rx_info,
  8611. * but *after* calling udp_tunnel_drop_rx_info.
  8612. */
  8613. if (features & NETIF_F_RX_UDP_TUNNEL_PORT) {
  8614. dev->features = features;
  8615. udp_tunnel_get_rx_info(dev);
  8616. } else {
  8617. udp_tunnel_drop_rx_info(dev);
  8618. }
  8619. }
  8620. if (diff & NETIF_F_HW_VLAN_CTAG_FILTER) {
  8621. if (features & NETIF_F_HW_VLAN_CTAG_FILTER) {
  8622. dev->features = features;
  8623. err |= vlan_get_rx_ctag_filter_info(dev);
  8624. } else {
  8625. vlan_drop_rx_ctag_filter_info(dev);
  8626. }
  8627. }
  8628. if (diff & NETIF_F_HW_VLAN_STAG_FILTER) {
  8629. if (features & NETIF_F_HW_VLAN_STAG_FILTER) {
  8630. dev->features = features;
  8631. err |= vlan_get_rx_stag_filter_info(dev);
  8632. } else {
  8633. vlan_drop_rx_stag_filter_info(dev);
  8634. }
  8635. }
  8636. dev->features = features;
  8637. }
  8638. return err < 0 ? 0 : 1;
  8639. }
  8640. /**
  8641. * netdev_update_features - recalculate device features
  8642. * @dev: the device to check
  8643. *
  8644. * Recalculate dev->features set and send notifications if it
  8645. * has changed. Should be called after driver or hardware dependent
  8646. * conditions might have changed that influence the features.
  8647. */
  8648. void netdev_update_features(struct net_device *dev)
  8649. {
  8650. if (__netdev_update_features(dev))
  8651. netdev_features_change(dev);
  8652. }
  8653. EXPORT_SYMBOL(netdev_update_features);
  8654. /**
  8655. * netdev_change_features - recalculate device features
  8656. * @dev: the device to check
  8657. *
  8658. * Recalculate dev->features set and send notifications even
  8659. * if they have not changed. Should be called instead of
  8660. * netdev_update_features() if also dev->vlan_features might
  8661. * have changed to allow the changes to be propagated to stacked
  8662. * VLAN devices.
  8663. */
  8664. void netdev_change_features(struct net_device *dev)
  8665. {
  8666. __netdev_update_features(dev);
  8667. netdev_features_change(dev);
  8668. }
  8669. EXPORT_SYMBOL(netdev_change_features);
  8670. /**
  8671. * netif_stacked_transfer_operstate - transfer operstate
  8672. * @rootdev: the root or lower level device to transfer state from
  8673. * @dev: the device to transfer operstate to
  8674. *
  8675. * Transfer operational state from root to device. This is normally
  8676. * called when a stacking relationship exists between the root
  8677. * device and the device(a leaf device).
  8678. */
  8679. void netif_stacked_transfer_operstate(const struct net_device *rootdev,
  8680. struct net_device *dev)
  8681. {
  8682. if (rootdev->operstate == IF_OPER_DORMANT)
  8683. netif_dormant_on(dev);
  8684. else
  8685. netif_dormant_off(dev);
  8686. if (rootdev->operstate == IF_OPER_TESTING)
  8687. netif_testing_on(dev);
  8688. else
  8689. netif_testing_off(dev);
  8690. if (netif_carrier_ok(rootdev))
  8691. netif_carrier_on(dev);
  8692. else
  8693. netif_carrier_off(dev);
  8694. }
  8695. EXPORT_SYMBOL(netif_stacked_transfer_operstate);
  8696. static int netif_alloc_rx_queues(struct net_device *dev)
  8697. {
  8698. unsigned int i, count = dev->num_rx_queues;
  8699. struct netdev_rx_queue *rx;
  8700. size_t sz = count * sizeof(*rx);
  8701. int err = 0;
  8702. BUG_ON(count < 1);
  8703. rx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
  8704. if (!rx)
  8705. return -ENOMEM;
  8706. dev->_rx = rx;
  8707. for (i = 0; i < count; i++) {
  8708. rx[i].dev = dev;
  8709. /* XDP RX-queue setup */
  8710. err = xdp_rxq_info_reg(&rx[i].xdp_rxq, dev, i, 0);
  8711. if (err < 0)
  8712. goto err_rxq_info;
  8713. }
  8714. return 0;
  8715. err_rxq_info:
  8716. /* Rollback successful reg's and free other resources */
  8717. while (i--)
  8718. xdp_rxq_info_unreg(&rx[i].xdp_rxq);
  8719. kvfree(dev->_rx);
  8720. dev->_rx = NULL;
  8721. return err;
  8722. }
  8723. static void netif_free_rx_queues(struct net_device *dev)
  8724. {
  8725. unsigned int i, count = dev->num_rx_queues;
  8726. /* netif_alloc_rx_queues alloc failed, resources have been unreg'ed */
  8727. if (!dev->_rx)
  8728. return;
  8729. for (i = 0; i < count; i++)
  8730. xdp_rxq_info_unreg(&dev->_rx[i].xdp_rxq);
  8731. kvfree(dev->_rx);
  8732. }
  8733. static void netdev_init_one_queue(struct net_device *dev,
  8734. struct netdev_queue *queue, void *_unused)
  8735. {
  8736. /* Initialize queue lock */
  8737. spin_lock_init(&queue->_xmit_lock);
  8738. netdev_set_xmit_lockdep_class(&queue->_xmit_lock, dev->type);
  8739. queue->xmit_lock_owner = -1;
  8740. netdev_queue_numa_node_write(queue, NUMA_NO_NODE);
  8741. queue->dev = dev;
  8742. #ifdef CONFIG_BQL
  8743. dql_init(&queue->dql, HZ);
  8744. #endif
  8745. }
  8746. static void netif_free_tx_queues(struct net_device *dev)
  8747. {
  8748. kvfree(dev->_tx);
  8749. }
  8750. static int netif_alloc_netdev_queues(struct net_device *dev)
  8751. {
  8752. unsigned int count = dev->num_tx_queues;
  8753. struct netdev_queue *tx;
  8754. size_t sz = count * sizeof(*tx);
  8755. if (count < 1 || count > 0xffff)
  8756. return -EINVAL;
  8757. tx = kvzalloc(sz, GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
  8758. if (!tx)
  8759. return -ENOMEM;
  8760. dev->_tx = tx;
  8761. netdev_for_each_tx_queue(dev, netdev_init_one_queue, NULL);
  8762. spin_lock_init(&dev->tx_global_lock);
  8763. return 0;
  8764. }
  8765. void netif_tx_stop_all_queues(struct net_device *dev)
  8766. {
  8767. unsigned int i;
  8768. for (i = 0; i < dev->num_tx_queues; i++) {
  8769. struct netdev_queue *txq = netdev_get_tx_queue(dev, i);
  8770. netif_tx_stop_queue(txq);
  8771. }
  8772. }
  8773. EXPORT_SYMBOL(netif_tx_stop_all_queues);
  8774. static int netdev_do_alloc_pcpu_stats(struct net_device *dev)
  8775. {
  8776. void __percpu *v;
  8777. /* Drivers implementing ndo_get_peer_dev must support tstat
  8778. * accounting, so that skb_do_redirect() can bump the dev's
  8779. * RX stats upon network namespace switch.
  8780. */
  8781. if (dev->netdev_ops->ndo_get_peer_dev &&
  8782. dev->pcpu_stat_type != NETDEV_PCPU_STAT_TSTATS)
  8783. return -EOPNOTSUPP;
  8784. switch (dev->pcpu_stat_type) {
  8785. case NETDEV_PCPU_STAT_NONE:
  8786. return 0;
  8787. case NETDEV_PCPU_STAT_LSTATS:
  8788. v = dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats);
  8789. break;
  8790. case NETDEV_PCPU_STAT_TSTATS:
  8791. v = dev->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
  8792. break;
  8793. case NETDEV_PCPU_STAT_DSTATS:
  8794. v = dev->dstats = netdev_alloc_pcpu_stats(struct pcpu_dstats);
  8795. break;
  8796. default:
  8797. return -EINVAL;
  8798. }
  8799. return v ? 0 : -ENOMEM;
  8800. }
  8801. static void netdev_do_free_pcpu_stats(struct net_device *dev)
  8802. {
  8803. switch (dev->pcpu_stat_type) {
  8804. case NETDEV_PCPU_STAT_NONE:
  8805. return;
  8806. case NETDEV_PCPU_STAT_LSTATS:
  8807. free_percpu(dev->lstats);
  8808. break;
  8809. case NETDEV_PCPU_STAT_TSTATS:
  8810. free_percpu(dev->tstats);
  8811. break;
  8812. case NETDEV_PCPU_STAT_DSTATS:
  8813. free_percpu(dev->dstats);
  8814. break;
  8815. }
  8816. }
  8817. static void netdev_free_phy_link_topology(struct net_device *dev)
  8818. {
  8819. struct phy_link_topology *topo = dev->link_topo;
  8820. if (IS_ENABLED(CONFIG_PHYLIB) && topo) {
  8821. xa_destroy(&topo->phys);
  8822. kfree(topo);
  8823. dev->link_topo = NULL;
  8824. }
  8825. }
  8826. /**
  8827. * register_netdevice() - register a network device
  8828. * @dev: device to register
  8829. *
  8830. * Take a prepared network device structure and make it externally accessible.
  8831. * A %NETDEV_REGISTER message is sent to the netdev notifier chain.
  8832. * Callers must hold the rtnl lock - you may want register_netdev()
  8833. * instead of this.
  8834. */
  8835. int register_netdevice(struct net_device *dev)
  8836. {
  8837. int ret;
  8838. struct net *net = dev_net(dev);
  8839. BUILD_BUG_ON(sizeof(netdev_features_t) * BITS_PER_BYTE <
  8840. NETDEV_FEATURE_COUNT);
  8841. BUG_ON(dev_boot_phase);
  8842. ASSERT_RTNL();
  8843. might_sleep();
  8844. /* When net_device's are persistent, this will be fatal. */
  8845. BUG_ON(dev->reg_state != NETREG_UNINITIALIZED);
  8846. BUG_ON(!net);
  8847. ret = ethtool_check_ops(dev->ethtool_ops);
  8848. if (ret)
  8849. return ret;
  8850. /* rss ctx ID 0 is reserved for the default context, start from 1 */
  8851. xa_init_flags(&dev->ethtool->rss_ctx, XA_FLAGS_ALLOC1);
  8852. mutex_init(&dev->ethtool->rss_lock);
  8853. spin_lock_init(&dev->addr_list_lock);
  8854. netdev_set_addr_lockdep_class(dev);
  8855. ret = dev_get_valid_name(net, dev, dev->name);
  8856. if (ret < 0)
  8857. goto out;
  8858. ret = -ENOMEM;
  8859. dev->name_node = netdev_name_node_head_alloc(dev);
  8860. if (!dev->name_node)
  8861. goto out;
  8862. /* Init, if this function is available */
  8863. if (dev->netdev_ops->ndo_init) {
  8864. ret = dev->netdev_ops->ndo_init(dev);
  8865. if (ret) {
  8866. if (ret > 0)
  8867. ret = -EIO;
  8868. goto err_free_name;
  8869. }
  8870. }
  8871. if (((dev->hw_features | dev->features) &
  8872. NETIF_F_HW_VLAN_CTAG_FILTER) &&
  8873. (!dev->netdev_ops->ndo_vlan_rx_add_vid ||
  8874. !dev->netdev_ops->ndo_vlan_rx_kill_vid)) {
  8875. netdev_WARN(dev, "Buggy VLAN acceleration in driver!\n");
  8876. ret = -EINVAL;
  8877. goto err_uninit;
  8878. }
  8879. ret = netdev_do_alloc_pcpu_stats(dev);
  8880. if (ret)
  8881. goto err_uninit;
  8882. ret = dev_index_reserve(net, dev->ifindex);
  8883. if (ret < 0)
  8884. goto err_free_pcpu;
  8885. dev->ifindex = ret;
  8886. /* Transfer changeable features to wanted_features and enable
  8887. * software offloads (GSO and GRO).
  8888. */
  8889. dev->hw_features |= (NETIF_F_SOFT_FEATURES | NETIF_F_SOFT_FEATURES_OFF);
  8890. dev->features |= NETIF_F_SOFT_FEATURES;
  8891. if (dev->udp_tunnel_nic_info) {
  8892. dev->features |= NETIF_F_RX_UDP_TUNNEL_PORT;
  8893. dev->hw_features |= NETIF_F_RX_UDP_TUNNEL_PORT;
  8894. }
  8895. dev->wanted_features = dev->features & dev->hw_features;
  8896. if (!(dev->flags & IFF_LOOPBACK))
  8897. dev->hw_features |= NETIF_F_NOCACHE_COPY;
  8898. /* If IPv4 TCP segmentation offload is supported we should also
  8899. * allow the device to enable segmenting the frame with the option
  8900. * of ignoring a static IP ID value. This doesn't enable the
  8901. * feature itself but allows the user to enable it later.
  8902. */
  8903. if (dev->hw_features & NETIF_F_TSO)
  8904. dev->hw_features |= NETIF_F_TSO_MANGLEID;
  8905. if (dev->vlan_features & NETIF_F_TSO)
  8906. dev->vlan_features |= NETIF_F_TSO_MANGLEID;
  8907. if (dev->mpls_features & NETIF_F_TSO)
  8908. dev->mpls_features |= NETIF_F_TSO_MANGLEID;
  8909. if (dev->hw_enc_features & NETIF_F_TSO)
  8910. dev->hw_enc_features |= NETIF_F_TSO_MANGLEID;
  8911. /* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
  8912. */
  8913. dev->vlan_features |= NETIF_F_HIGHDMA;
  8914. /* Make NETIF_F_SG inheritable to tunnel devices.
  8915. */
  8916. dev->hw_enc_features |= NETIF_F_SG | NETIF_F_GSO_PARTIAL;
  8917. /* Make NETIF_F_SG inheritable to MPLS.
  8918. */
  8919. dev->mpls_features |= NETIF_F_SG;
  8920. ret = call_netdevice_notifiers(NETDEV_POST_INIT, dev);
  8921. ret = notifier_to_errno(ret);
  8922. if (ret)
  8923. goto err_ifindex_release;
  8924. ret = netdev_register_kobject(dev);
  8925. WRITE_ONCE(dev->reg_state, ret ? NETREG_UNREGISTERED : NETREG_REGISTERED);
  8926. if (ret)
  8927. goto err_uninit_notify;
  8928. __netdev_update_features(dev);
  8929. /*
  8930. * Default initial state at registry is that the
  8931. * device is present.
  8932. */
  8933. set_bit(__LINK_STATE_PRESENT, &dev->state);
  8934. linkwatch_init_dev(dev);
  8935. dev_init_scheduler(dev);
  8936. netdev_hold(dev, &dev->dev_registered_tracker, GFP_KERNEL);
  8937. list_netdevice(dev);
  8938. add_device_randomness(dev->dev_addr, dev->addr_len);
  8939. /* If the device has permanent device address, driver should
  8940. * set dev_addr and also addr_assign_type should be set to
  8941. * NET_ADDR_PERM (default value).
  8942. */
  8943. if (dev->addr_assign_type == NET_ADDR_PERM)
  8944. memcpy(dev->perm_addr, dev->dev_addr, dev->addr_len);
  8945. /* Notify protocols, that a new device appeared. */
  8946. ret = call_netdevice_notifiers(NETDEV_REGISTER, dev);
  8947. ret = notifier_to_errno(ret);
  8948. if (ret) {
  8949. /* Expect explicit free_netdev() on failure */
  8950. dev->needs_free_netdev = false;
  8951. unregister_netdevice_queue(dev, NULL);
  8952. goto out;
  8953. }
  8954. /*
  8955. * Prevent userspace races by waiting until the network
  8956. * device is fully setup before sending notifications.
  8957. */
  8958. if (!dev->rtnl_link_ops ||
  8959. dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
  8960. rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
  8961. out:
  8962. return ret;
  8963. err_uninit_notify:
  8964. call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
  8965. err_ifindex_release:
  8966. dev_index_release(net, dev->ifindex);
  8967. err_free_pcpu:
  8968. netdev_do_free_pcpu_stats(dev);
  8969. err_uninit:
  8970. if (dev->netdev_ops->ndo_uninit)
  8971. dev->netdev_ops->ndo_uninit(dev);
  8972. if (dev->priv_destructor)
  8973. dev->priv_destructor(dev);
  8974. err_free_name:
  8975. netdev_name_node_free(dev->name_node);
  8976. goto out;
  8977. }
  8978. EXPORT_SYMBOL(register_netdevice);
  8979. /* Initialize the core of a dummy net device.
  8980. * This is useful if you are calling this function after alloc_netdev(),
  8981. * since it does not memset the net_device fields.
  8982. */
  8983. static void init_dummy_netdev_core(struct net_device *dev)
  8984. {
  8985. /* make sure we BUG if trying to hit standard
  8986. * register/unregister code path
  8987. */
  8988. dev->reg_state = NETREG_DUMMY;
  8989. /* NAPI wants this */
  8990. INIT_LIST_HEAD(&dev->napi_list);
  8991. /* a dummy interface is started by default */
  8992. set_bit(__LINK_STATE_PRESENT, &dev->state);
  8993. set_bit(__LINK_STATE_START, &dev->state);
  8994. /* napi_busy_loop stats accounting wants this */
  8995. dev_net_set(dev, &init_net);
  8996. /* Note : We dont allocate pcpu_refcnt for dummy devices,
  8997. * because users of this 'device' dont need to change
  8998. * its refcount.
  8999. */
  9000. }
  9001. /**
  9002. * init_dummy_netdev - init a dummy network device for NAPI
  9003. * @dev: device to init
  9004. *
  9005. * This takes a network device structure and initializes the minimum
  9006. * amount of fields so it can be used to schedule NAPI polls without
  9007. * registering a full blown interface. This is to be used by drivers
  9008. * that need to tie several hardware interfaces to a single NAPI
  9009. * poll scheduler due to HW limitations.
  9010. */
  9011. void init_dummy_netdev(struct net_device *dev)
  9012. {
  9013. /* Clear everything. Note we don't initialize spinlocks
  9014. * as they aren't supposed to be taken by any of the
  9015. * NAPI code and this dummy netdev is supposed to be
  9016. * only ever used for NAPI polls
  9017. */
  9018. memset(dev, 0, sizeof(struct net_device));
  9019. init_dummy_netdev_core(dev);
  9020. }
  9021. EXPORT_SYMBOL_GPL(init_dummy_netdev);
  9022. /**
  9023. * register_netdev - register a network device
  9024. * @dev: device to register
  9025. *
  9026. * Take a completed network device structure and add it to the kernel
  9027. * interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
  9028. * chain. 0 is returned on success. A negative errno code is returned
  9029. * on a failure to set up the device, or if the name is a duplicate.
  9030. *
  9031. * This is a wrapper around register_netdevice that takes the rtnl semaphore
  9032. * and expands the device name if you passed a format string to
  9033. * alloc_netdev.
  9034. */
  9035. int register_netdev(struct net_device *dev)
  9036. {
  9037. int err;
  9038. if (rtnl_lock_killable())
  9039. return -EINTR;
  9040. err = register_netdevice(dev);
  9041. rtnl_unlock();
  9042. return err;
  9043. }
  9044. EXPORT_SYMBOL(register_netdev);
  9045. int netdev_refcnt_read(const struct net_device *dev)
  9046. {
  9047. #ifdef CONFIG_PCPU_DEV_REFCNT
  9048. int i, refcnt = 0;
  9049. for_each_possible_cpu(i)
  9050. refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
  9051. return refcnt;
  9052. #else
  9053. return refcount_read(&dev->dev_refcnt);
  9054. #endif
  9055. }
  9056. EXPORT_SYMBOL(netdev_refcnt_read);
  9057. int netdev_unregister_timeout_secs __read_mostly = 10;
  9058. #define WAIT_REFS_MIN_MSECS 1
  9059. #define WAIT_REFS_MAX_MSECS 250
  9060. /**
  9061. * netdev_wait_allrefs_any - wait until all references are gone.
  9062. * @list: list of net_devices to wait on
  9063. *
  9064. * This is called when unregistering network devices.
  9065. *
  9066. * Any protocol or device that holds a reference should register
  9067. * for netdevice notification, and cleanup and put back the
  9068. * reference if they receive an UNREGISTER event.
  9069. * We can get stuck here if buggy protocols don't correctly
  9070. * call dev_put.
  9071. */
  9072. static struct net_device *netdev_wait_allrefs_any(struct list_head *list)
  9073. {
  9074. unsigned long rebroadcast_time, warning_time;
  9075. struct net_device *dev;
  9076. int wait = 0;
  9077. rebroadcast_time = warning_time = jiffies;
  9078. list_for_each_entry(dev, list, todo_list)
  9079. if (netdev_refcnt_read(dev) == 1)
  9080. return dev;
  9081. while (true) {
  9082. if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
  9083. rtnl_lock();
  9084. /* Rebroadcast unregister notification */
  9085. list_for_each_entry(dev, list, todo_list)
  9086. call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
  9087. __rtnl_unlock();
  9088. rcu_barrier();
  9089. rtnl_lock();
  9090. list_for_each_entry(dev, list, todo_list)
  9091. if (test_bit(__LINK_STATE_LINKWATCH_PENDING,
  9092. &dev->state)) {
  9093. /* We must not have linkwatch events
  9094. * pending on unregister. If this
  9095. * happens, we simply run the queue
  9096. * unscheduled, resulting in a noop
  9097. * for this device.
  9098. */
  9099. linkwatch_run_queue();
  9100. break;
  9101. }
  9102. __rtnl_unlock();
  9103. rebroadcast_time = jiffies;
  9104. }
  9105. rcu_barrier();
  9106. if (!wait) {
  9107. wait = WAIT_REFS_MIN_MSECS;
  9108. } else {
  9109. msleep(wait);
  9110. wait = min(wait << 1, WAIT_REFS_MAX_MSECS);
  9111. }
  9112. list_for_each_entry(dev, list, todo_list)
  9113. if (netdev_refcnt_read(dev) == 1)
  9114. return dev;
  9115. if (time_after(jiffies, warning_time +
  9116. READ_ONCE(netdev_unregister_timeout_secs) * HZ)) {
  9117. list_for_each_entry(dev, list, todo_list) {
  9118. pr_emerg("unregister_netdevice: waiting for %s to become free. Usage count = %d\n",
  9119. dev->name, netdev_refcnt_read(dev));
  9120. ref_tracker_dir_print(&dev->refcnt_tracker, 10);
  9121. }
  9122. warning_time = jiffies;
  9123. }
  9124. }
  9125. }
  9126. /* The sequence is:
  9127. *
  9128. * rtnl_lock();
  9129. * ...
  9130. * register_netdevice(x1);
  9131. * register_netdevice(x2);
  9132. * ...
  9133. * unregister_netdevice(y1);
  9134. * unregister_netdevice(y2);
  9135. * ...
  9136. * rtnl_unlock();
  9137. * free_netdev(y1);
  9138. * free_netdev(y2);
  9139. *
  9140. * We are invoked by rtnl_unlock().
  9141. * This allows us to deal with problems:
  9142. * 1) We can delete sysfs objects which invoke hotplug
  9143. * without deadlocking with linkwatch via keventd.
  9144. * 2) Since we run with the RTNL semaphore not held, we can sleep
  9145. * safely in order to wait for the netdev refcnt to drop to zero.
  9146. *
  9147. * We must not return until all unregister events added during
  9148. * the interval the lock was held have been completed.
  9149. */
  9150. void netdev_run_todo(void)
  9151. {
  9152. struct net_device *dev, *tmp;
  9153. struct list_head list;
  9154. int cnt;
  9155. #ifdef CONFIG_LOCKDEP
  9156. struct list_head unlink_list;
  9157. list_replace_init(&net_unlink_list, &unlink_list);
  9158. while (!list_empty(&unlink_list)) {
  9159. struct net_device *dev = list_first_entry(&unlink_list,
  9160. struct net_device,
  9161. unlink_list);
  9162. list_del_init(&dev->unlink_list);
  9163. dev->nested_level = dev->lower_level - 1;
  9164. }
  9165. #endif
  9166. /* Snapshot list, allow later requests */
  9167. list_replace_init(&net_todo_list, &list);
  9168. __rtnl_unlock();
  9169. /* Wait for rcu callbacks to finish before next phase */
  9170. if (!list_empty(&list))
  9171. rcu_barrier();
  9172. list_for_each_entry_safe(dev, tmp, &list, todo_list) {
  9173. if (unlikely(dev->reg_state != NETREG_UNREGISTERING)) {
  9174. netdev_WARN(dev, "run_todo but not unregistering\n");
  9175. list_del(&dev->todo_list);
  9176. continue;
  9177. }
  9178. WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERED);
  9179. linkwatch_sync_dev(dev);
  9180. }
  9181. cnt = 0;
  9182. while (!list_empty(&list)) {
  9183. dev = netdev_wait_allrefs_any(&list);
  9184. list_del(&dev->todo_list);
  9185. /* paranoia */
  9186. BUG_ON(netdev_refcnt_read(dev) != 1);
  9187. BUG_ON(!list_empty(&dev->ptype_all));
  9188. BUG_ON(!list_empty(&dev->ptype_specific));
  9189. WARN_ON(rcu_access_pointer(dev->ip_ptr));
  9190. WARN_ON(rcu_access_pointer(dev->ip6_ptr));
  9191. netdev_do_free_pcpu_stats(dev);
  9192. if (dev->priv_destructor)
  9193. dev->priv_destructor(dev);
  9194. if (dev->needs_free_netdev)
  9195. free_netdev(dev);
  9196. cnt++;
  9197. /* Free network device */
  9198. kobject_put(&dev->dev.kobj);
  9199. }
  9200. if (cnt && atomic_sub_and_test(cnt, &dev_unreg_count))
  9201. wake_up(&netdev_unregistering_wq);
  9202. }
  9203. /* Collate per-cpu network dstats statistics
  9204. *
  9205. * Read per-cpu network statistics from dev->dstats and populate the related
  9206. * fields in @s.
  9207. */
  9208. static void dev_fetch_dstats(struct rtnl_link_stats64 *s,
  9209. const struct pcpu_dstats __percpu *dstats)
  9210. {
  9211. int cpu;
  9212. for_each_possible_cpu(cpu) {
  9213. u64 rx_packets, rx_bytes, rx_drops;
  9214. u64 tx_packets, tx_bytes, tx_drops;
  9215. const struct pcpu_dstats *stats;
  9216. unsigned int start;
  9217. stats = per_cpu_ptr(dstats, cpu);
  9218. do {
  9219. start = u64_stats_fetch_begin(&stats->syncp);
  9220. rx_packets = u64_stats_read(&stats->rx_packets);
  9221. rx_bytes = u64_stats_read(&stats->rx_bytes);
  9222. rx_drops = u64_stats_read(&stats->rx_drops);
  9223. tx_packets = u64_stats_read(&stats->tx_packets);
  9224. tx_bytes = u64_stats_read(&stats->tx_bytes);
  9225. tx_drops = u64_stats_read(&stats->tx_drops);
  9226. } while (u64_stats_fetch_retry(&stats->syncp, start));
  9227. s->rx_packets += rx_packets;
  9228. s->rx_bytes += rx_bytes;
  9229. s->rx_dropped += rx_drops;
  9230. s->tx_packets += tx_packets;
  9231. s->tx_bytes += tx_bytes;
  9232. s->tx_dropped += tx_drops;
  9233. }
  9234. }
  9235. /* ndo_get_stats64 implementation for dtstats-based accounting.
  9236. *
  9237. * Populate @s from dev->stats and dev->dstats. This is used internally by the
  9238. * core for NETDEV_PCPU_STAT_DSTAT-type stats collection.
  9239. */
  9240. static void dev_get_dstats64(const struct net_device *dev,
  9241. struct rtnl_link_stats64 *s)
  9242. {
  9243. netdev_stats_to_stats64(s, &dev->stats);
  9244. dev_fetch_dstats(s, dev->dstats);
  9245. }
  9246. /* Convert net_device_stats to rtnl_link_stats64. rtnl_link_stats64 has
  9247. * all the same fields in the same order as net_device_stats, with only
  9248. * the type differing, but rtnl_link_stats64 may have additional fields
  9249. * at the end for newer counters.
  9250. */
  9251. void netdev_stats_to_stats64(struct rtnl_link_stats64 *stats64,
  9252. const struct net_device_stats *netdev_stats)
  9253. {
  9254. size_t i, n = sizeof(*netdev_stats) / sizeof(atomic_long_t);
  9255. const atomic_long_t *src = (atomic_long_t *)netdev_stats;
  9256. u64 *dst = (u64 *)stats64;
  9257. BUILD_BUG_ON(n > sizeof(*stats64) / sizeof(u64));
  9258. for (i = 0; i < n; i++)
  9259. dst[i] = (unsigned long)atomic_long_read(&src[i]);
  9260. /* zero out counters that only exist in rtnl_link_stats64 */
  9261. memset((char *)stats64 + n * sizeof(u64), 0,
  9262. sizeof(*stats64) - n * sizeof(u64));
  9263. }
  9264. EXPORT_SYMBOL(netdev_stats_to_stats64);
  9265. static __cold struct net_device_core_stats __percpu *netdev_core_stats_alloc(
  9266. struct net_device *dev)
  9267. {
  9268. struct net_device_core_stats __percpu *p;
  9269. p = alloc_percpu_gfp(struct net_device_core_stats,
  9270. GFP_ATOMIC | __GFP_NOWARN);
  9271. if (p && cmpxchg(&dev->core_stats, NULL, p))
  9272. free_percpu(p);
  9273. /* This READ_ONCE() pairs with the cmpxchg() above */
  9274. return READ_ONCE(dev->core_stats);
  9275. }
  9276. noinline void netdev_core_stats_inc(struct net_device *dev, u32 offset)
  9277. {
  9278. /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
  9279. struct net_device_core_stats __percpu *p = READ_ONCE(dev->core_stats);
  9280. unsigned long __percpu *field;
  9281. if (unlikely(!p)) {
  9282. p = netdev_core_stats_alloc(dev);
  9283. if (!p)
  9284. return;
  9285. }
  9286. field = (unsigned long __percpu *)((void __percpu *)p + offset);
  9287. this_cpu_inc(*field);
  9288. }
  9289. EXPORT_SYMBOL_GPL(netdev_core_stats_inc);
  9290. /**
  9291. * dev_get_stats - get network device statistics
  9292. * @dev: device to get statistics from
  9293. * @storage: place to store stats
  9294. *
  9295. * Get network statistics from device. Return @storage.
  9296. * The device driver may provide its own method by setting
  9297. * dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
  9298. * otherwise the internal statistics structure is used.
  9299. */
  9300. struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
  9301. struct rtnl_link_stats64 *storage)
  9302. {
  9303. const struct net_device_ops *ops = dev->netdev_ops;
  9304. const struct net_device_core_stats __percpu *p;
  9305. if (ops->ndo_get_stats64) {
  9306. memset(storage, 0, sizeof(*storage));
  9307. ops->ndo_get_stats64(dev, storage);
  9308. } else if (ops->ndo_get_stats) {
  9309. netdev_stats_to_stats64(storage, ops->ndo_get_stats(dev));
  9310. } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_TSTATS) {
  9311. dev_get_tstats64(dev, storage);
  9312. } else if (dev->pcpu_stat_type == NETDEV_PCPU_STAT_DSTATS) {
  9313. dev_get_dstats64(dev, storage);
  9314. } else {
  9315. netdev_stats_to_stats64(storage, &dev->stats);
  9316. }
  9317. /* This READ_ONCE() pairs with the write in netdev_core_stats_alloc() */
  9318. p = READ_ONCE(dev->core_stats);
  9319. if (p) {
  9320. const struct net_device_core_stats *core_stats;
  9321. int i;
  9322. for_each_possible_cpu(i) {
  9323. core_stats = per_cpu_ptr(p, i);
  9324. storage->rx_dropped += READ_ONCE(core_stats->rx_dropped);
  9325. storage->tx_dropped += READ_ONCE(core_stats->tx_dropped);
  9326. storage->rx_nohandler += READ_ONCE(core_stats->rx_nohandler);
  9327. storage->rx_otherhost_dropped += READ_ONCE(core_stats->rx_otherhost_dropped);
  9328. }
  9329. }
  9330. return storage;
  9331. }
  9332. EXPORT_SYMBOL(dev_get_stats);
  9333. /**
  9334. * dev_fetch_sw_netstats - get per-cpu network device statistics
  9335. * @s: place to store stats
  9336. * @netstats: per-cpu network stats to read from
  9337. *
  9338. * Read per-cpu network statistics and populate the related fields in @s.
  9339. */
  9340. void dev_fetch_sw_netstats(struct rtnl_link_stats64 *s,
  9341. const struct pcpu_sw_netstats __percpu *netstats)
  9342. {
  9343. int cpu;
  9344. for_each_possible_cpu(cpu) {
  9345. u64 rx_packets, rx_bytes, tx_packets, tx_bytes;
  9346. const struct pcpu_sw_netstats *stats;
  9347. unsigned int start;
  9348. stats = per_cpu_ptr(netstats, cpu);
  9349. do {
  9350. start = u64_stats_fetch_begin(&stats->syncp);
  9351. rx_packets = u64_stats_read(&stats->rx_packets);
  9352. rx_bytes = u64_stats_read(&stats->rx_bytes);
  9353. tx_packets = u64_stats_read(&stats->tx_packets);
  9354. tx_bytes = u64_stats_read(&stats->tx_bytes);
  9355. } while (u64_stats_fetch_retry(&stats->syncp, start));
  9356. s->rx_packets += rx_packets;
  9357. s->rx_bytes += rx_bytes;
  9358. s->tx_packets += tx_packets;
  9359. s->tx_bytes += tx_bytes;
  9360. }
  9361. }
  9362. EXPORT_SYMBOL_GPL(dev_fetch_sw_netstats);
  9363. /**
  9364. * dev_get_tstats64 - ndo_get_stats64 implementation
  9365. * @dev: device to get statistics from
  9366. * @s: place to store stats
  9367. *
  9368. * Populate @s from dev->stats and dev->tstats. Can be used as
  9369. * ndo_get_stats64() callback.
  9370. */
  9371. void dev_get_tstats64(struct net_device *dev, struct rtnl_link_stats64 *s)
  9372. {
  9373. netdev_stats_to_stats64(s, &dev->stats);
  9374. dev_fetch_sw_netstats(s, dev->tstats);
  9375. }
  9376. EXPORT_SYMBOL_GPL(dev_get_tstats64);
  9377. struct netdev_queue *dev_ingress_queue_create(struct net_device *dev)
  9378. {
  9379. struct netdev_queue *queue = dev_ingress_queue(dev);
  9380. #ifdef CONFIG_NET_CLS_ACT
  9381. if (queue)
  9382. return queue;
  9383. queue = kzalloc(sizeof(*queue), GFP_KERNEL);
  9384. if (!queue)
  9385. return NULL;
  9386. netdev_init_one_queue(dev, queue, NULL);
  9387. RCU_INIT_POINTER(queue->qdisc, &noop_qdisc);
  9388. RCU_INIT_POINTER(queue->qdisc_sleeping, &noop_qdisc);
  9389. rcu_assign_pointer(dev->ingress_queue, queue);
  9390. #endif
  9391. return queue;
  9392. }
  9393. static const struct ethtool_ops default_ethtool_ops;
  9394. void netdev_set_default_ethtool_ops(struct net_device *dev,
  9395. const struct ethtool_ops *ops)
  9396. {
  9397. if (dev->ethtool_ops == &default_ethtool_ops)
  9398. dev->ethtool_ops = ops;
  9399. }
  9400. EXPORT_SYMBOL_GPL(netdev_set_default_ethtool_ops);
  9401. /**
  9402. * netdev_sw_irq_coalesce_default_on() - enable SW IRQ coalescing by default
  9403. * @dev: netdev to enable the IRQ coalescing on
  9404. *
  9405. * Sets a conservative default for SW IRQ coalescing. Users can use
  9406. * sysfs attributes to override the default values.
  9407. */
  9408. void netdev_sw_irq_coalesce_default_on(struct net_device *dev)
  9409. {
  9410. WARN_ON(dev->reg_state == NETREG_REGISTERED);
  9411. if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
  9412. dev->gro_flush_timeout = 20000;
  9413. dev->napi_defer_hard_irqs = 1;
  9414. }
  9415. }
  9416. EXPORT_SYMBOL_GPL(netdev_sw_irq_coalesce_default_on);
  9417. /**
  9418. * alloc_netdev_mqs - allocate network device
  9419. * @sizeof_priv: size of private data to allocate space for
  9420. * @name: device name format string
  9421. * @name_assign_type: origin of device name
  9422. * @setup: callback to initialize device
  9423. * @txqs: the number of TX subqueues to allocate
  9424. * @rxqs: the number of RX subqueues to allocate
  9425. *
  9426. * Allocates a struct net_device with private data area for driver use
  9427. * and performs basic initialization. Also allocates subqueue structs
  9428. * for each queue on the device.
  9429. */
  9430. struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
  9431. unsigned char name_assign_type,
  9432. void (*setup)(struct net_device *),
  9433. unsigned int txqs, unsigned int rxqs)
  9434. {
  9435. struct net_device *dev;
  9436. BUG_ON(strlen(name) >= sizeof(dev->name));
  9437. if (txqs < 1) {
  9438. pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
  9439. return NULL;
  9440. }
  9441. if (rxqs < 1) {
  9442. pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
  9443. return NULL;
  9444. }
  9445. dev = kvzalloc(struct_size(dev, priv, sizeof_priv),
  9446. GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL);
  9447. if (!dev)
  9448. return NULL;
  9449. dev->priv_len = sizeof_priv;
  9450. ref_tracker_dir_init(&dev->refcnt_tracker, 128, name);
  9451. #ifdef CONFIG_PCPU_DEV_REFCNT
  9452. dev->pcpu_refcnt = alloc_percpu(int);
  9453. if (!dev->pcpu_refcnt)
  9454. goto free_dev;
  9455. __dev_hold(dev);
  9456. #else
  9457. refcount_set(&dev->dev_refcnt, 1);
  9458. #endif
  9459. if (dev_addr_init(dev))
  9460. goto free_pcpu;
  9461. dev_mc_init(dev);
  9462. dev_uc_init(dev);
  9463. dev_net_set(dev, &init_net);
  9464. dev->gso_max_size = GSO_LEGACY_MAX_SIZE;
  9465. dev->xdp_zc_max_segs = 1;
  9466. dev->gso_max_segs = GSO_MAX_SEGS;
  9467. dev->gro_max_size = GRO_LEGACY_MAX_SIZE;
  9468. dev->gso_ipv4_max_size = GSO_LEGACY_MAX_SIZE;
  9469. dev->gro_ipv4_max_size = GRO_LEGACY_MAX_SIZE;
  9470. dev->tso_max_size = TSO_LEGACY_MAX_SIZE;
  9471. dev->tso_max_segs = TSO_MAX_SEGS;
  9472. dev->upper_level = 1;
  9473. dev->lower_level = 1;
  9474. #ifdef CONFIG_LOCKDEP
  9475. dev->nested_level = 0;
  9476. INIT_LIST_HEAD(&dev->unlink_list);
  9477. #endif
  9478. INIT_LIST_HEAD(&dev->napi_list);
  9479. INIT_LIST_HEAD(&dev->unreg_list);
  9480. INIT_LIST_HEAD(&dev->close_list);
  9481. INIT_LIST_HEAD(&dev->link_watch_list);
  9482. INIT_LIST_HEAD(&dev->adj_list.upper);
  9483. INIT_LIST_HEAD(&dev->adj_list.lower);
  9484. INIT_LIST_HEAD(&dev->ptype_all);
  9485. INIT_LIST_HEAD(&dev->ptype_specific);
  9486. INIT_LIST_HEAD(&dev->net_notifier_list);
  9487. #ifdef CONFIG_NET_SCHED
  9488. hash_init(dev->qdisc_hash);
  9489. #endif
  9490. dev->priv_flags = IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM;
  9491. setup(dev);
  9492. if (!dev->tx_queue_len) {
  9493. dev->priv_flags |= IFF_NO_QUEUE;
  9494. dev->tx_queue_len = DEFAULT_TX_QUEUE_LEN;
  9495. }
  9496. dev->num_tx_queues = txqs;
  9497. dev->real_num_tx_queues = txqs;
  9498. if (netif_alloc_netdev_queues(dev))
  9499. goto free_all;
  9500. dev->num_rx_queues = rxqs;
  9501. dev->real_num_rx_queues = rxqs;
  9502. if (netif_alloc_rx_queues(dev))
  9503. goto free_all;
  9504. dev->ethtool = kzalloc(sizeof(*dev->ethtool), GFP_KERNEL_ACCOUNT);
  9505. if (!dev->ethtool)
  9506. goto free_all;
  9507. strscpy(dev->name, name);
  9508. dev->name_assign_type = name_assign_type;
  9509. dev->group = INIT_NETDEV_GROUP;
  9510. if (!dev->ethtool_ops)
  9511. dev->ethtool_ops = &default_ethtool_ops;
  9512. nf_hook_netdev_init(dev);
  9513. return dev;
  9514. free_all:
  9515. free_netdev(dev);
  9516. return NULL;
  9517. free_pcpu:
  9518. #ifdef CONFIG_PCPU_DEV_REFCNT
  9519. free_percpu(dev->pcpu_refcnt);
  9520. free_dev:
  9521. #endif
  9522. kvfree(dev);
  9523. return NULL;
  9524. }
  9525. EXPORT_SYMBOL(alloc_netdev_mqs);
  9526. /**
  9527. * free_netdev - free network device
  9528. * @dev: device
  9529. *
  9530. * This function does the last stage of destroying an allocated device
  9531. * interface. The reference to the device object is released. If this
  9532. * is the last reference then it will be freed.Must be called in process
  9533. * context.
  9534. */
  9535. void free_netdev(struct net_device *dev)
  9536. {
  9537. struct napi_struct *p, *n;
  9538. might_sleep();
  9539. /* When called immediately after register_netdevice() failed the unwind
  9540. * handling may still be dismantling the device. Handle that case by
  9541. * deferring the free.
  9542. */
  9543. if (dev->reg_state == NETREG_UNREGISTERING) {
  9544. ASSERT_RTNL();
  9545. dev->needs_free_netdev = true;
  9546. return;
  9547. }
  9548. kfree(dev->ethtool);
  9549. netif_free_tx_queues(dev);
  9550. netif_free_rx_queues(dev);
  9551. kfree(rcu_dereference_protected(dev->ingress_queue, 1));
  9552. /* Flush device addresses */
  9553. dev_addr_flush(dev);
  9554. list_for_each_entry_safe(p, n, &dev->napi_list, dev_list)
  9555. netif_napi_del(p);
  9556. ref_tracker_dir_exit(&dev->refcnt_tracker);
  9557. #ifdef CONFIG_PCPU_DEV_REFCNT
  9558. free_percpu(dev->pcpu_refcnt);
  9559. dev->pcpu_refcnt = NULL;
  9560. #endif
  9561. free_percpu(dev->core_stats);
  9562. dev->core_stats = NULL;
  9563. free_percpu(dev->xdp_bulkq);
  9564. dev->xdp_bulkq = NULL;
  9565. netdev_free_phy_link_topology(dev);
  9566. /* Compatibility with error handling in drivers */
  9567. if (dev->reg_state == NETREG_UNINITIALIZED ||
  9568. dev->reg_state == NETREG_DUMMY) {
  9569. kvfree(dev);
  9570. return;
  9571. }
  9572. BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
  9573. WRITE_ONCE(dev->reg_state, NETREG_RELEASED);
  9574. /* will free via device release */
  9575. put_device(&dev->dev);
  9576. }
  9577. EXPORT_SYMBOL(free_netdev);
  9578. /**
  9579. * alloc_netdev_dummy - Allocate and initialize a dummy net device.
  9580. * @sizeof_priv: size of private data to allocate space for
  9581. *
  9582. * Return: the allocated net_device on success, NULL otherwise
  9583. */
  9584. struct net_device *alloc_netdev_dummy(int sizeof_priv)
  9585. {
  9586. return alloc_netdev(sizeof_priv, "dummy#", NET_NAME_UNKNOWN,
  9587. init_dummy_netdev_core);
  9588. }
  9589. EXPORT_SYMBOL_GPL(alloc_netdev_dummy);
  9590. /**
  9591. * synchronize_net - Synchronize with packet receive processing
  9592. *
  9593. * Wait for packets currently being received to be done.
  9594. * Does not block later packets from starting.
  9595. */
  9596. void synchronize_net(void)
  9597. {
  9598. might_sleep();
  9599. if (rtnl_is_locked())
  9600. synchronize_rcu_expedited();
  9601. else
  9602. synchronize_rcu();
  9603. }
  9604. EXPORT_SYMBOL(synchronize_net);
  9605. static void netdev_rss_contexts_free(struct net_device *dev)
  9606. {
  9607. struct ethtool_rxfh_context *ctx;
  9608. unsigned long context;
  9609. mutex_lock(&dev->ethtool->rss_lock);
  9610. xa_for_each(&dev->ethtool->rss_ctx, context, ctx) {
  9611. struct ethtool_rxfh_param rxfh;
  9612. rxfh.indir = ethtool_rxfh_context_indir(ctx);
  9613. rxfh.key = ethtool_rxfh_context_key(ctx);
  9614. rxfh.hfunc = ctx->hfunc;
  9615. rxfh.input_xfrm = ctx->input_xfrm;
  9616. rxfh.rss_context = context;
  9617. rxfh.rss_delete = true;
  9618. xa_erase(&dev->ethtool->rss_ctx, context);
  9619. if (dev->ethtool_ops->create_rxfh_context)
  9620. dev->ethtool_ops->remove_rxfh_context(dev, ctx,
  9621. context, NULL);
  9622. else
  9623. dev->ethtool_ops->set_rxfh(dev, &rxfh, NULL);
  9624. kfree(ctx);
  9625. }
  9626. xa_destroy(&dev->ethtool->rss_ctx);
  9627. mutex_unlock(&dev->ethtool->rss_lock);
  9628. }
  9629. /**
  9630. * unregister_netdevice_queue - remove device from the kernel
  9631. * @dev: device
  9632. * @head: list
  9633. *
  9634. * This function shuts down a device interface and removes it
  9635. * from the kernel tables.
  9636. * If head not NULL, device is queued to be unregistered later.
  9637. *
  9638. * Callers must hold the rtnl semaphore. You may want
  9639. * unregister_netdev() instead of this.
  9640. */
  9641. void unregister_netdevice_queue(struct net_device *dev, struct list_head *head)
  9642. {
  9643. ASSERT_RTNL();
  9644. if (head) {
  9645. list_move_tail(&dev->unreg_list, head);
  9646. } else {
  9647. LIST_HEAD(single);
  9648. list_add(&dev->unreg_list, &single);
  9649. unregister_netdevice_many(&single);
  9650. }
  9651. }
  9652. EXPORT_SYMBOL(unregister_netdevice_queue);
  9653. void unregister_netdevice_many_notify(struct list_head *head,
  9654. u32 portid, const struct nlmsghdr *nlh)
  9655. {
  9656. struct net_device *dev, *tmp;
  9657. LIST_HEAD(close_head);
  9658. int cnt = 0;
  9659. BUG_ON(dev_boot_phase);
  9660. ASSERT_RTNL();
  9661. if (list_empty(head))
  9662. return;
  9663. list_for_each_entry_safe(dev, tmp, head, unreg_list) {
  9664. /* Some devices call without registering
  9665. * for initialization unwind. Remove those
  9666. * devices and proceed with the remaining.
  9667. */
  9668. if (dev->reg_state == NETREG_UNINITIALIZED) {
  9669. pr_debug("unregister_netdevice: device %s/%p never was registered\n",
  9670. dev->name, dev);
  9671. WARN_ON(1);
  9672. list_del(&dev->unreg_list);
  9673. continue;
  9674. }
  9675. dev->dismantle = true;
  9676. BUG_ON(dev->reg_state != NETREG_REGISTERED);
  9677. }
  9678. /* If device is running, close it first. */
  9679. list_for_each_entry(dev, head, unreg_list)
  9680. list_add_tail(&dev->close_list, &close_head);
  9681. dev_close_many(&close_head, true);
  9682. list_for_each_entry(dev, head, unreg_list) {
  9683. /* And unlink it from device chain. */
  9684. unlist_netdevice(dev);
  9685. WRITE_ONCE(dev->reg_state, NETREG_UNREGISTERING);
  9686. }
  9687. flush_all_backlogs();
  9688. synchronize_net();
  9689. list_for_each_entry(dev, head, unreg_list) {
  9690. struct sk_buff *skb = NULL;
  9691. /* Shutdown queueing discipline. */
  9692. dev_shutdown(dev);
  9693. dev_tcx_uninstall(dev);
  9694. dev_xdp_uninstall(dev);
  9695. bpf_dev_bound_netdev_unregister(dev);
  9696. dev_dmabuf_uninstall(dev);
  9697. netdev_offload_xstats_disable_all(dev);
  9698. /* Notify protocols, that we are about to destroy
  9699. * this device. They should clean all the things.
  9700. */
  9701. call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
  9702. if (!dev->rtnl_link_ops ||
  9703. dev->rtnl_link_state == RTNL_LINK_INITIALIZED)
  9704. skb = rtmsg_ifinfo_build_skb(RTM_DELLINK, dev, ~0U, 0,
  9705. GFP_KERNEL, NULL, 0,
  9706. portid, nlh);
  9707. /*
  9708. * Flush the unicast and multicast chains
  9709. */
  9710. dev_uc_flush(dev);
  9711. dev_mc_flush(dev);
  9712. netdev_name_node_alt_flush(dev);
  9713. netdev_name_node_free(dev->name_node);
  9714. netdev_rss_contexts_free(dev);
  9715. call_netdevice_notifiers(NETDEV_PRE_UNINIT, dev);
  9716. if (dev->netdev_ops->ndo_uninit)
  9717. dev->netdev_ops->ndo_uninit(dev);
  9718. mutex_destroy(&dev->ethtool->rss_lock);
  9719. if (skb)
  9720. rtmsg_ifinfo_send(skb, dev, GFP_KERNEL, portid, nlh);
  9721. /* Notifier chain MUST detach us all upper devices. */
  9722. WARN_ON(netdev_has_any_upper_dev(dev));
  9723. WARN_ON(netdev_has_any_lower_dev(dev));
  9724. /* Remove entries from kobject tree */
  9725. netdev_unregister_kobject(dev);
  9726. #ifdef CONFIG_XPS
  9727. /* Remove XPS queueing entries */
  9728. netif_reset_xps_queues_gt(dev, 0);
  9729. #endif
  9730. }
  9731. synchronize_net();
  9732. list_for_each_entry(dev, head, unreg_list) {
  9733. netdev_put(dev, &dev->dev_registered_tracker);
  9734. net_set_todo(dev);
  9735. cnt++;
  9736. }
  9737. atomic_add(cnt, &dev_unreg_count);
  9738. list_del(head);
  9739. }
  9740. /**
  9741. * unregister_netdevice_many - unregister many devices
  9742. * @head: list of devices
  9743. *
  9744. * Note: As most callers use a stack allocated list_head,
  9745. * we force a list_del() to make sure stack won't be corrupted later.
  9746. */
  9747. void unregister_netdevice_many(struct list_head *head)
  9748. {
  9749. unregister_netdevice_many_notify(head, 0, NULL);
  9750. }
  9751. EXPORT_SYMBOL(unregister_netdevice_many);
  9752. /**
  9753. * unregister_netdev - remove device from the kernel
  9754. * @dev: device
  9755. *
  9756. * This function shuts down a device interface and removes it
  9757. * from the kernel tables.
  9758. *
  9759. * This is just a wrapper for unregister_netdevice that takes
  9760. * the rtnl semaphore. In general you want to use this and not
  9761. * unregister_netdevice.
  9762. */
  9763. void unregister_netdev(struct net_device *dev)
  9764. {
  9765. rtnl_lock();
  9766. unregister_netdevice(dev);
  9767. rtnl_unlock();
  9768. }
  9769. EXPORT_SYMBOL(unregister_netdev);
  9770. /**
  9771. * __dev_change_net_namespace - move device to different nethost namespace
  9772. * @dev: device
  9773. * @net: network namespace
  9774. * @pat: If not NULL name pattern to try if the current device name
  9775. * is already taken in the destination network namespace.
  9776. * @new_ifindex: If not zero, specifies device index in the target
  9777. * namespace.
  9778. *
  9779. * This function shuts down a device interface and moves it
  9780. * to a new network namespace. On success 0 is returned, on
  9781. * a failure a netagive errno code is returned.
  9782. *
  9783. * Callers must hold the rtnl semaphore.
  9784. */
  9785. int __dev_change_net_namespace(struct net_device *dev, struct net *net,
  9786. const char *pat, int new_ifindex)
  9787. {
  9788. struct netdev_name_node *name_node;
  9789. struct net *net_old = dev_net(dev);
  9790. char new_name[IFNAMSIZ] = {};
  9791. int err, new_nsid;
  9792. ASSERT_RTNL();
  9793. /* Don't allow namespace local devices to be moved. */
  9794. err = -EINVAL;
  9795. if (dev->netns_local)
  9796. goto out;
  9797. /* Ensure the device has been registered */
  9798. if (dev->reg_state != NETREG_REGISTERED)
  9799. goto out;
  9800. /* Get out if there is nothing todo */
  9801. err = 0;
  9802. if (net_eq(net_old, net))
  9803. goto out;
  9804. /* Pick the destination device name, and ensure
  9805. * we can use it in the destination network namespace.
  9806. */
  9807. err = -EEXIST;
  9808. if (netdev_name_in_use(net, dev->name)) {
  9809. /* We get here if we can't use the current device name */
  9810. if (!pat)
  9811. goto out;
  9812. err = dev_prep_valid_name(net, dev, pat, new_name, EEXIST);
  9813. if (err < 0)
  9814. goto out;
  9815. }
  9816. /* Check that none of the altnames conflicts. */
  9817. err = -EEXIST;
  9818. netdev_for_each_altname(dev, name_node)
  9819. if (netdev_name_in_use(net, name_node->name))
  9820. goto out;
  9821. /* Check that new_ifindex isn't used yet. */
  9822. if (new_ifindex) {
  9823. err = dev_index_reserve(net, new_ifindex);
  9824. if (err < 0)
  9825. goto out;
  9826. } else {
  9827. /* If there is an ifindex conflict assign a new one */
  9828. err = dev_index_reserve(net, dev->ifindex);
  9829. if (err == -EBUSY)
  9830. err = dev_index_reserve(net, 0);
  9831. if (err < 0)
  9832. goto out;
  9833. new_ifindex = err;
  9834. }
  9835. /*
  9836. * And now a mini version of register_netdevice unregister_netdevice.
  9837. */
  9838. /* If device is running close it first. */
  9839. dev_close(dev);
  9840. /* And unlink it from device chain */
  9841. unlist_netdevice(dev);
  9842. synchronize_net();
  9843. /* Shutdown queueing discipline. */
  9844. dev_shutdown(dev);
  9845. /* Notify protocols, that we are about to destroy
  9846. * this device. They should clean all the things.
  9847. *
  9848. * Note that dev->reg_state stays at NETREG_REGISTERED.
  9849. * This is wanted because this way 8021q and macvlan know
  9850. * the device is just moving and can keep their slaves up.
  9851. */
  9852. call_netdevice_notifiers(NETDEV_UNREGISTER, dev);
  9853. rcu_barrier();
  9854. new_nsid = peernet2id_alloc(dev_net(dev), net, GFP_KERNEL);
  9855. rtmsg_ifinfo_newnet(RTM_DELLINK, dev, ~0U, GFP_KERNEL, &new_nsid,
  9856. new_ifindex);
  9857. /*
  9858. * Flush the unicast and multicast chains
  9859. */
  9860. dev_uc_flush(dev);
  9861. dev_mc_flush(dev);
  9862. /* Send a netdev-removed uevent to the old namespace */
  9863. kobject_uevent(&dev->dev.kobj, KOBJ_REMOVE);
  9864. netdev_adjacent_del_links(dev);
  9865. /* Move per-net netdevice notifiers that are following the netdevice */
  9866. move_netdevice_notifiers_dev_net(dev, net);
  9867. /* Actually switch the network namespace */
  9868. dev_net_set(dev, net);
  9869. dev->ifindex = new_ifindex;
  9870. if (new_name[0]) {
  9871. /* Rename the netdev to prepared name */
  9872. write_seqlock_bh(&netdev_rename_lock);
  9873. strscpy(dev->name, new_name, IFNAMSIZ);
  9874. write_sequnlock_bh(&netdev_rename_lock);
  9875. }
  9876. /* Fixup kobjects */
  9877. dev_set_uevent_suppress(&dev->dev, 1);
  9878. err = device_rename(&dev->dev, dev->name);
  9879. dev_set_uevent_suppress(&dev->dev, 0);
  9880. WARN_ON(err);
  9881. /* Send a netdev-add uevent to the new namespace */
  9882. kobject_uevent(&dev->dev.kobj, KOBJ_ADD);
  9883. netdev_adjacent_add_links(dev);
  9884. /* Adapt owner in case owning user namespace of target network
  9885. * namespace is different from the original one.
  9886. */
  9887. err = netdev_change_owner(dev, net_old, net);
  9888. WARN_ON(err);
  9889. /* Add the device back in the hashes */
  9890. list_netdevice(dev);
  9891. /* Notify protocols, that a new device appeared. */
  9892. call_netdevice_notifiers(NETDEV_REGISTER, dev);
  9893. /*
  9894. * Prevent userspace races by waiting until the network
  9895. * device is fully setup before sending notifications.
  9896. */
  9897. rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U, GFP_KERNEL, 0, NULL);
  9898. synchronize_net();
  9899. err = 0;
  9900. out:
  9901. return err;
  9902. }
  9903. EXPORT_SYMBOL_GPL(__dev_change_net_namespace);
  9904. static int dev_cpu_dead(unsigned int oldcpu)
  9905. {
  9906. struct sk_buff **list_skb;
  9907. struct sk_buff *skb;
  9908. unsigned int cpu;
  9909. struct softnet_data *sd, *oldsd, *remsd = NULL;
  9910. local_irq_disable();
  9911. cpu = smp_processor_id();
  9912. sd = &per_cpu(softnet_data, cpu);
  9913. oldsd = &per_cpu(softnet_data, oldcpu);
  9914. /* Find end of our completion_queue. */
  9915. list_skb = &sd->completion_queue;
  9916. while (*list_skb)
  9917. list_skb = &(*list_skb)->next;
  9918. /* Append completion queue from offline CPU. */
  9919. *list_skb = oldsd->completion_queue;
  9920. oldsd->completion_queue = NULL;
  9921. /* Append output queue from offline CPU. */
  9922. if (oldsd->output_queue) {
  9923. *sd->output_queue_tailp = oldsd->output_queue;
  9924. sd->output_queue_tailp = oldsd->output_queue_tailp;
  9925. oldsd->output_queue = NULL;
  9926. oldsd->output_queue_tailp = &oldsd->output_queue;
  9927. }
  9928. /* Append NAPI poll list from offline CPU, with one exception :
  9929. * process_backlog() must be called by cpu owning percpu backlog.
  9930. * We properly handle process_queue & input_pkt_queue later.
  9931. */
  9932. while (!list_empty(&oldsd->poll_list)) {
  9933. struct napi_struct *napi = list_first_entry(&oldsd->poll_list,
  9934. struct napi_struct,
  9935. poll_list);
  9936. list_del_init(&napi->poll_list);
  9937. if (napi->poll == process_backlog)
  9938. napi->state &= NAPIF_STATE_THREADED;
  9939. else
  9940. ____napi_schedule(sd, napi);
  9941. }
  9942. raise_softirq_irqoff(NET_TX_SOFTIRQ);
  9943. local_irq_enable();
  9944. if (!use_backlog_threads()) {
  9945. #ifdef CONFIG_RPS
  9946. remsd = oldsd->rps_ipi_list;
  9947. oldsd->rps_ipi_list = NULL;
  9948. #endif
  9949. /* send out pending IPI's on offline CPU */
  9950. net_rps_send_ipi(remsd);
  9951. }
  9952. /* Process offline CPU's input_pkt_queue */
  9953. while ((skb = __skb_dequeue(&oldsd->process_queue))) {
  9954. netif_rx(skb);
  9955. rps_input_queue_head_incr(oldsd);
  9956. }
  9957. while ((skb = skb_dequeue(&oldsd->input_pkt_queue))) {
  9958. netif_rx(skb);
  9959. rps_input_queue_head_incr(oldsd);
  9960. }
  9961. return 0;
  9962. }
  9963. /**
  9964. * netdev_increment_features - increment feature set by one
  9965. * @all: current feature set
  9966. * @one: new feature set
  9967. * @mask: mask feature set
  9968. *
  9969. * Computes a new feature set after adding a device with feature set
  9970. * @one to the master device with current feature set @all. Will not
  9971. * enable anything that is off in @mask. Returns the new feature set.
  9972. */
  9973. netdev_features_t netdev_increment_features(netdev_features_t all,
  9974. netdev_features_t one, netdev_features_t mask)
  9975. {
  9976. if (mask & NETIF_F_HW_CSUM)
  9977. mask |= NETIF_F_CSUM_MASK;
  9978. mask |= NETIF_F_VLAN_CHALLENGED;
  9979. all |= one & (NETIF_F_ONE_FOR_ALL | NETIF_F_CSUM_MASK) & mask;
  9980. all &= one | ~NETIF_F_ALL_FOR_ALL;
  9981. /* If one device supports hw checksumming, set for all. */
  9982. if (all & NETIF_F_HW_CSUM)
  9983. all &= ~(NETIF_F_CSUM_MASK & ~NETIF_F_HW_CSUM);
  9984. return all;
  9985. }
  9986. EXPORT_SYMBOL(netdev_increment_features);
  9987. static struct hlist_head * __net_init netdev_create_hash(void)
  9988. {
  9989. int i;
  9990. struct hlist_head *hash;
  9991. hash = kmalloc_array(NETDEV_HASHENTRIES, sizeof(*hash), GFP_KERNEL);
  9992. if (hash != NULL)
  9993. for (i = 0; i < NETDEV_HASHENTRIES; i++)
  9994. INIT_HLIST_HEAD(&hash[i]);
  9995. return hash;
  9996. }
  9997. /* Initialize per network namespace state */
  9998. static int __net_init netdev_init(struct net *net)
  9999. {
  10000. BUILD_BUG_ON(GRO_HASH_BUCKETS >
  10001. 8 * sizeof_field(struct napi_struct, gro_bitmask));
  10002. INIT_LIST_HEAD(&net->dev_base_head);
  10003. net->dev_name_head = netdev_create_hash();
  10004. if (net->dev_name_head == NULL)
  10005. goto err_name;
  10006. net->dev_index_head = netdev_create_hash();
  10007. if (net->dev_index_head == NULL)
  10008. goto err_idx;
  10009. xa_init_flags(&net->dev_by_index, XA_FLAGS_ALLOC1);
  10010. RAW_INIT_NOTIFIER_HEAD(&net->netdev_chain);
  10011. return 0;
  10012. err_idx:
  10013. kfree(net->dev_name_head);
  10014. err_name:
  10015. return -ENOMEM;
  10016. }
  10017. /**
  10018. * netdev_drivername - network driver for the device
  10019. * @dev: network device
  10020. *
  10021. * Determine network driver for device.
  10022. */
  10023. const char *netdev_drivername(const struct net_device *dev)
  10024. {
  10025. const struct device_driver *driver;
  10026. const struct device *parent;
  10027. const char *empty = "";
  10028. parent = dev->dev.parent;
  10029. if (!parent)
  10030. return empty;
  10031. driver = parent->driver;
  10032. if (driver && driver->name)
  10033. return driver->name;
  10034. return empty;
  10035. }
  10036. static void __netdev_printk(const char *level, const struct net_device *dev,
  10037. struct va_format *vaf)
  10038. {
  10039. if (dev && dev->dev.parent) {
  10040. dev_printk_emit(level[1] - '0',
  10041. dev->dev.parent,
  10042. "%s %s %s%s: %pV",
  10043. dev_driver_string(dev->dev.parent),
  10044. dev_name(dev->dev.parent),
  10045. netdev_name(dev), netdev_reg_state(dev),
  10046. vaf);
  10047. } else if (dev) {
  10048. printk("%s%s%s: %pV",
  10049. level, netdev_name(dev), netdev_reg_state(dev), vaf);
  10050. } else {
  10051. printk("%s(NULL net_device): %pV", level, vaf);
  10052. }
  10053. }
  10054. void netdev_printk(const char *level, const struct net_device *dev,
  10055. const char *format, ...)
  10056. {
  10057. struct va_format vaf;
  10058. va_list args;
  10059. va_start(args, format);
  10060. vaf.fmt = format;
  10061. vaf.va = &args;
  10062. __netdev_printk(level, dev, &vaf);
  10063. va_end(args);
  10064. }
  10065. EXPORT_SYMBOL(netdev_printk);
  10066. #define define_netdev_printk_level(func, level) \
  10067. void func(const struct net_device *dev, const char *fmt, ...) \
  10068. { \
  10069. struct va_format vaf; \
  10070. va_list args; \
  10071. \
  10072. va_start(args, fmt); \
  10073. \
  10074. vaf.fmt = fmt; \
  10075. vaf.va = &args; \
  10076. \
  10077. __netdev_printk(level, dev, &vaf); \
  10078. \
  10079. va_end(args); \
  10080. } \
  10081. EXPORT_SYMBOL(func);
  10082. define_netdev_printk_level(netdev_emerg, KERN_EMERG);
  10083. define_netdev_printk_level(netdev_alert, KERN_ALERT);
  10084. define_netdev_printk_level(netdev_crit, KERN_CRIT);
  10085. define_netdev_printk_level(netdev_err, KERN_ERR);
  10086. define_netdev_printk_level(netdev_warn, KERN_WARNING);
  10087. define_netdev_printk_level(netdev_notice, KERN_NOTICE);
  10088. define_netdev_printk_level(netdev_info, KERN_INFO);
  10089. static void __net_exit netdev_exit(struct net *net)
  10090. {
  10091. kfree(net->dev_name_head);
  10092. kfree(net->dev_index_head);
  10093. xa_destroy(&net->dev_by_index);
  10094. if (net != &init_net)
  10095. WARN_ON_ONCE(!list_empty(&net->dev_base_head));
  10096. }
  10097. static struct pernet_operations __net_initdata netdev_net_ops = {
  10098. .init = netdev_init,
  10099. .exit = netdev_exit,
  10100. };
  10101. static void __net_exit default_device_exit_net(struct net *net)
  10102. {
  10103. struct netdev_name_node *name_node, *tmp;
  10104. struct net_device *dev, *aux;
  10105. /*
  10106. * Push all migratable network devices back to the
  10107. * initial network namespace
  10108. */
  10109. ASSERT_RTNL();
  10110. for_each_netdev_safe(net, dev, aux) {
  10111. int err;
  10112. char fb_name[IFNAMSIZ];
  10113. /* Ignore unmoveable devices (i.e. loopback) */
  10114. if (dev->netns_local)
  10115. continue;
  10116. /* Leave virtual devices for the generic cleanup */
  10117. if (dev->rtnl_link_ops && !dev->rtnl_link_ops->netns_refund)
  10118. continue;
  10119. /* Push remaining network devices to init_net */
  10120. snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
  10121. if (netdev_name_in_use(&init_net, fb_name))
  10122. snprintf(fb_name, IFNAMSIZ, "dev%%d");
  10123. netdev_for_each_altname_safe(dev, name_node, tmp)
  10124. if (netdev_name_in_use(&init_net, name_node->name))
  10125. __netdev_name_node_alt_destroy(name_node);
  10126. err = dev_change_net_namespace(dev, &init_net, fb_name);
  10127. if (err) {
  10128. pr_emerg("%s: failed to move %s to init_net: %d\n",
  10129. __func__, dev->name, err);
  10130. BUG();
  10131. }
  10132. }
  10133. }
  10134. static void __net_exit default_device_exit_batch(struct list_head *net_list)
  10135. {
  10136. /* At exit all network devices most be removed from a network
  10137. * namespace. Do this in the reverse order of registration.
  10138. * Do this across as many network namespaces as possible to
  10139. * improve batching efficiency.
  10140. */
  10141. struct net_device *dev;
  10142. struct net *net;
  10143. LIST_HEAD(dev_kill_list);
  10144. rtnl_lock();
  10145. list_for_each_entry(net, net_list, exit_list) {
  10146. default_device_exit_net(net);
  10147. cond_resched();
  10148. }
  10149. list_for_each_entry(net, net_list, exit_list) {
  10150. for_each_netdev_reverse(net, dev) {
  10151. if (dev->rtnl_link_ops && dev->rtnl_link_ops->dellink)
  10152. dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
  10153. else
  10154. unregister_netdevice_queue(dev, &dev_kill_list);
  10155. }
  10156. }
  10157. unregister_netdevice_many(&dev_kill_list);
  10158. rtnl_unlock();
  10159. }
  10160. static struct pernet_operations __net_initdata default_device_ops = {
  10161. .exit_batch = default_device_exit_batch,
  10162. };
  10163. static void __init net_dev_struct_check(void)
  10164. {
  10165. /* TX read-mostly hotpath */
  10166. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, priv_flags_fast);
  10167. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, netdev_ops);
  10168. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, header_ops);
  10169. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, _tx);
  10170. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, real_num_tx_queues);
  10171. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_size);
  10172. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_ipv4_max_size);
  10173. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_max_segs);
  10174. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, gso_partial_features);
  10175. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, num_tc);
  10176. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, mtu);
  10177. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, needed_headroom);
  10178. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tc_to_txq);
  10179. #ifdef CONFIG_XPS
  10180. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, xps_maps);
  10181. #endif
  10182. #ifdef CONFIG_NETFILTER_EGRESS
  10183. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, nf_hooks_egress);
  10184. #endif
  10185. #ifdef CONFIG_NET_XGRESS
  10186. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_tx, tcx_egress);
  10187. #endif
  10188. CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_tx, 160);
  10189. /* TXRX read-mostly hotpath */
  10190. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, lstats);
  10191. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, state);
  10192. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, flags);
  10193. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, hard_header_len);
  10194. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, features);
  10195. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_txrx, ip6_ptr);
  10196. CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_txrx, 46);
  10197. /* RX read-mostly hotpath */
  10198. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ptype_specific);
  10199. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, ifindex);
  10200. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, real_num_rx_queues);
  10201. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, _rx);
  10202. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_flush_timeout);
  10203. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, napi_defer_hard_irqs);
  10204. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_max_size);
  10205. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, gro_ipv4_max_size);
  10206. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler);
  10207. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, rx_handler_data);
  10208. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, nd_net);
  10209. #ifdef CONFIG_NETPOLL
  10210. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, npinfo);
  10211. #endif
  10212. #ifdef CONFIG_NET_XGRESS
  10213. CACHELINE_ASSERT_GROUP_MEMBER(struct net_device, net_device_read_rx, tcx_ingress);
  10214. #endif
  10215. CACHELINE_ASSERT_GROUP_SIZE(struct net_device, net_device_read_rx, 104);
  10216. }
  10217. /*
  10218. * Initialize the DEV module. At boot time this walks the device list and
  10219. * unhooks any devices that fail to initialise (normally hardware not
  10220. * present) and leaves us with a valid list of present and active devices.
  10221. *
  10222. */
  10223. /* We allocate 256 pages for each CPU if PAGE_SHIFT is 12 */
  10224. #define SYSTEM_PERCPU_PAGE_POOL_SIZE ((1 << 20) / PAGE_SIZE)
  10225. static int net_page_pool_create(int cpuid)
  10226. {
  10227. #if IS_ENABLED(CONFIG_PAGE_POOL)
  10228. struct page_pool_params page_pool_params = {
  10229. .pool_size = SYSTEM_PERCPU_PAGE_POOL_SIZE,
  10230. .flags = PP_FLAG_SYSTEM_POOL,
  10231. .nid = cpu_to_mem(cpuid),
  10232. };
  10233. struct page_pool *pp_ptr;
  10234. pp_ptr = page_pool_create_percpu(&page_pool_params, cpuid);
  10235. if (IS_ERR(pp_ptr))
  10236. return -ENOMEM;
  10237. per_cpu(system_page_pool, cpuid) = pp_ptr;
  10238. #endif
  10239. return 0;
  10240. }
  10241. static int backlog_napi_should_run(unsigned int cpu)
  10242. {
  10243. struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
  10244. struct napi_struct *napi = &sd->backlog;
  10245. return test_bit(NAPI_STATE_SCHED_THREADED, &napi->state);
  10246. }
  10247. static void run_backlog_napi(unsigned int cpu)
  10248. {
  10249. struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
  10250. napi_threaded_poll_loop(&sd->backlog);
  10251. }
  10252. static void backlog_napi_setup(unsigned int cpu)
  10253. {
  10254. struct softnet_data *sd = per_cpu_ptr(&softnet_data, cpu);
  10255. struct napi_struct *napi = &sd->backlog;
  10256. napi->thread = this_cpu_read(backlog_napi);
  10257. set_bit(NAPI_STATE_THREADED, &napi->state);
  10258. }
  10259. static struct smp_hotplug_thread backlog_threads = {
  10260. .store = &backlog_napi,
  10261. .thread_should_run = backlog_napi_should_run,
  10262. .thread_fn = run_backlog_napi,
  10263. .thread_comm = "backlog_napi/%u",
  10264. .setup = backlog_napi_setup,
  10265. };
  10266. /*
  10267. * This is called single threaded during boot, so no need
  10268. * to take the rtnl semaphore.
  10269. */
  10270. static int __init net_dev_init(void)
  10271. {
  10272. int i, rc = -ENOMEM;
  10273. BUG_ON(!dev_boot_phase);
  10274. net_dev_struct_check();
  10275. if (dev_proc_init())
  10276. goto out;
  10277. if (netdev_kobject_init())
  10278. goto out;
  10279. for (i = 0; i < PTYPE_HASH_SIZE; i++)
  10280. INIT_LIST_HEAD(&ptype_base[i]);
  10281. if (register_pernet_subsys(&netdev_net_ops))
  10282. goto out;
  10283. /*
  10284. * Initialise the packet receive queues.
  10285. */
  10286. for_each_possible_cpu(i) {
  10287. struct work_struct *flush = per_cpu_ptr(&flush_works, i);
  10288. struct softnet_data *sd = &per_cpu(softnet_data, i);
  10289. INIT_WORK(flush, flush_backlog);
  10290. skb_queue_head_init(&sd->input_pkt_queue);
  10291. skb_queue_head_init(&sd->process_queue);
  10292. #ifdef CONFIG_XFRM_OFFLOAD
  10293. skb_queue_head_init(&sd->xfrm_backlog);
  10294. #endif
  10295. INIT_LIST_HEAD(&sd->poll_list);
  10296. sd->output_queue_tailp = &sd->output_queue;
  10297. #ifdef CONFIG_RPS
  10298. INIT_CSD(&sd->csd, rps_trigger_softirq, sd);
  10299. sd->cpu = i;
  10300. #endif
  10301. INIT_CSD(&sd->defer_csd, trigger_rx_softirq, sd);
  10302. spin_lock_init(&sd->defer_lock);
  10303. init_gro_hash(&sd->backlog);
  10304. sd->backlog.poll = process_backlog;
  10305. sd->backlog.weight = weight_p;
  10306. INIT_LIST_HEAD(&sd->backlog.poll_list);
  10307. if (net_page_pool_create(i))
  10308. goto out;
  10309. }
  10310. if (use_backlog_threads())
  10311. smpboot_register_percpu_thread(&backlog_threads);
  10312. dev_boot_phase = 0;
  10313. /* The loopback device is special if any other network devices
  10314. * is present in a network namespace the loopback device must
  10315. * be present. Since we now dynamically allocate and free the
  10316. * loopback device ensure this invariant is maintained by
  10317. * keeping the loopback device as the first device on the
  10318. * list of network devices. Ensuring the loopback devices
  10319. * is the first device that appears and the last network device
  10320. * that disappears.
  10321. */
  10322. if (register_pernet_device(&loopback_net_ops))
  10323. goto out;
  10324. if (register_pernet_device(&default_device_ops))
  10325. goto out;
  10326. open_softirq(NET_TX_SOFTIRQ, net_tx_action);
  10327. open_softirq(NET_RX_SOFTIRQ, net_rx_action);
  10328. rc = cpuhp_setup_state_nocalls(CPUHP_NET_DEV_DEAD, "net/dev:dead",
  10329. NULL, dev_cpu_dead);
  10330. WARN_ON(rc < 0);
  10331. rc = 0;
  10332. /* avoid static key IPIs to isolated CPUs */
  10333. if (housekeeping_enabled(HK_TYPE_MISC))
  10334. net_enable_timestamp();
  10335. out:
  10336. if (rc < 0) {
  10337. for_each_possible_cpu(i) {
  10338. struct page_pool *pp_ptr;
  10339. pp_ptr = per_cpu(system_page_pool, i);
  10340. if (!pp_ptr)
  10341. continue;
  10342. page_pool_destroy(pp_ptr);
  10343. per_cpu(system_page_pool, i) = NULL;
  10344. }
  10345. }
  10346. return rc;
  10347. }
  10348. subsys_initcall(net_dev_init);