i915_gem.c 160 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982
  1. /*
  2. * Copyright © 2008-2015 Intel Corporation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice (including the next
  12. * paragraph) shall be included in all copies or substantial portions of the
  13. * Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  18. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21. * IN THE SOFTWARE.
  22. *
  23. * Authors:
  24. * Eric Anholt <eric@anholt.net>
  25. *
  26. */
  27. #include <drm/drmP.h>
  28. #include <drm/drm_vma_manager.h>
  29. #include <drm/i915_drm.h>
  30. #include "i915_drv.h"
  31. #include "i915_gem_clflush.h"
  32. #include "i915_vgpu.h"
  33. #include "i915_trace.h"
  34. #include "intel_drv.h"
  35. #include "intel_frontbuffer.h"
  36. #include "intel_mocs.h"
  37. #include "i915_gemfs.h"
  38. #include <linux/dma-fence-array.h>
  39. #include <linux/kthread.h>
  40. #include <linux/reservation.h>
  41. #include <linux/shmem_fs.h>
  42. #include <linux/slab.h>
  43. #include <linux/stop_machine.h>
  44. #include <linux/swap.h>
  45. #include <linux/pci.h>
  46. #include <linux/dma-buf.h>
  47. static void i915_gem_flush_free_objects(struct drm_i915_private *i915);
  48. static bool cpu_write_needs_clflush(struct drm_i915_gem_object *obj)
  49. {
  50. if (obj->cache_dirty)
  51. return false;
  52. if (!(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE))
  53. return true;
  54. return obj->pin_global; /* currently in use by HW, keep flushed */
  55. }
  56. static int
  57. insert_mappable_node(struct i915_ggtt *ggtt,
  58. struct drm_mm_node *node, u32 size)
  59. {
  60. memset(node, 0, sizeof(*node));
  61. return drm_mm_insert_node_in_range(&ggtt->base.mm, node,
  62. size, 0, I915_COLOR_UNEVICTABLE,
  63. 0, ggtt->mappable_end,
  64. DRM_MM_INSERT_LOW);
  65. }
  66. static void
  67. remove_mappable_node(struct drm_mm_node *node)
  68. {
  69. drm_mm_remove_node(node);
  70. }
  71. /* some bookkeeping */
  72. static void i915_gem_info_add_obj(struct drm_i915_private *dev_priv,
  73. u64 size)
  74. {
  75. spin_lock(&dev_priv->mm.object_stat_lock);
  76. dev_priv->mm.object_count++;
  77. dev_priv->mm.object_memory += size;
  78. spin_unlock(&dev_priv->mm.object_stat_lock);
  79. }
  80. static void i915_gem_info_remove_obj(struct drm_i915_private *dev_priv,
  81. u64 size)
  82. {
  83. spin_lock(&dev_priv->mm.object_stat_lock);
  84. dev_priv->mm.object_count--;
  85. dev_priv->mm.object_memory -= size;
  86. spin_unlock(&dev_priv->mm.object_stat_lock);
  87. }
  88. static int
  89. i915_gem_wait_for_error(struct i915_gpu_error *error)
  90. {
  91. int ret;
  92. might_sleep();
  93. /*
  94. * Only wait 10 seconds for the gpu reset to complete to avoid hanging
  95. * userspace. If it takes that long something really bad is going on and
  96. * we should simply try to bail out and fail as gracefully as possible.
  97. */
  98. ret = wait_event_interruptible_timeout(error->reset_queue,
  99. !i915_reset_backoff(error),
  100. I915_RESET_TIMEOUT);
  101. if (ret == 0) {
  102. DRM_ERROR("Timed out waiting for the gpu reset to complete\n");
  103. return -EIO;
  104. } else if (ret < 0) {
  105. return ret;
  106. } else {
  107. return 0;
  108. }
  109. }
  110. int i915_mutex_lock_interruptible(struct drm_device *dev)
  111. {
  112. struct drm_i915_private *dev_priv = to_i915(dev);
  113. int ret;
  114. ret = i915_gem_wait_for_error(&dev_priv->gpu_error);
  115. if (ret)
  116. return ret;
  117. ret = mutex_lock_interruptible(&dev->struct_mutex);
  118. if (ret)
  119. return ret;
  120. return 0;
  121. }
  122. int
  123. i915_gem_get_aperture_ioctl(struct drm_device *dev, void *data,
  124. struct drm_file *file)
  125. {
  126. struct drm_i915_private *dev_priv = to_i915(dev);
  127. struct i915_ggtt *ggtt = &dev_priv->ggtt;
  128. struct drm_i915_gem_get_aperture *args = data;
  129. struct i915_vma *vma;
  130. u64 pinned;
  131. pinned = ggtt->base.reserved;
  132. mutex_lock(&dev->struct_mutex);
  133. list_for_each_entry(vma, &ggtt->base.active_list, vm_link)
  134. if (i915_vma_is_pinned(vma))
  135. pinned += vma->node.size;
  136. list_for_each_entry(vma, &ggtt->base.inactive_list, vm_link)
  137. if (i915_vma_is_pinned(vma))
  138. pinned += vma->node.size;
  139. mutex_unlock(&dev->struct_mutex);
  140. args->aper_size = ggtt->base.total;
  141. args->aper_available_size = args->aper_size - pinned;
  142. return 0;
  143. }
  144. static int i915_gem_object_get_pages_phys(struct drm_i915_gem_object *obj)
  145. {
  146. struct address_space *mapping = obj->base.filp->f_mapping;
  147. drm_dma_handle_t *phys;
  148. struct sg_table *st;
  149. struct scatterlist *sg;
  150. char *vaddr;
  151. int i;
  152. int err;
  153. if (WARN_ON(i915_gem_object_needs_bit17_swizzle(obj)))
  154. return -EINVAL;
  155. /* Always aligning to the object size, allows a single allocation
  156. * to handle all possible callers, and given typical object sizes,
  157. * the alignment of the buddy allocation will naturally match.
  158. */
  159. phys = drm_pci_alloc(obj->base.dev,
  160. roundup_pow_of_two(obj->base.size),
  161. roundup_pow_of_two(obj->base.size));
  162. if (!phys)
  163. return -ENOMEM;
  164. vaddr = phys->vaddr;
  165. for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
  166. struct page *page;
  167. char *src;
  168. page = shmem_read_mapping_page(mapping, i);
  169. if (IS_ERR(page)) {
  170. err = PTR_ERR(page);
  171. goto err_phys;
  172. }
  173. src = kmap_atomic(page);
  174. memcpy(vaddr, src, PAGE_SIZE);
  175. drm_clflush_virt_range(vaddr, PAGE_SIZE);
  176. kunmap_atomic(src);
  177. put_page(page);
  178. vaddr += PAGE_SIZE;
  179. }
  180. i915_gem_chipset_flush(to_i915(obj->base.dev));
  181. st = kmalloc(sizeof(*st), GFP_KERNEL);
  182. if (!st) {
  183. err = -ENOMEM;
  184. goto err_phys;
  185. }
  186. if (sg_alloc_table(st, 1, GFP_KERNEL)) {
  187. kfree(st);
  188. err = -ENOMEM;
  189. goto err_phys;
  190. }
  191. sg = st->sgl;
  192. sg->offset = 0;
  193. sg->length = obj->base.size;
  194. sg_dma_address(sg) = phys->busaddr;
  195. sg_dma_len(sg) = obj->base.size;
  196. obj->phys_handle = phys;
  197. __i915_gem_object_set_pages(obj, st, sg->length);
  198. return 0;
  199. err_phys:
  200. drm_pci_free(obj->base.dev, phys);
  201. return err;
  202. }
  203. static void __start_cpu_write(struct drm_i915_gem_object *obj)
  204. {
  205. obj->read_domains = I915_GEM_DOMAIN_CPU;
  206. obj->write_domain = I915_GEM_DOMAIN_CPU;
  207. if (cpu_write_needs_clflush(obj))
  208. obj->cache_dirty = true;
  209. }
  210. static void
  211. __i915_gem_object_release_shmem(struct drm_i915_gem_object *obj,
  212. struct sg_table *pages,
  213. bool needs_clflush)
  214. {
  215. GEM_BUG_ON(obj->mm.madv == __I915_MADV_PURGED);
  216. if (obj->mm.madv == I915_MADV_DONTNEED)
  217. obj->mm.dirty = false;
  218. if (needs_clflush &&
  219. (obj->read_domains & I915_GEM_DOMAIN_CPU) == 0 &&
  220. !(obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ))
  221. drm_clflush_sg(pages);
  222. __start_cpu_write(obj);
  223. }
  224. static void
  225. i915_gem_object_put_pages_phys(struct drm_i915_gem_object *obj,
  226. struct sg_table *pages)
  227. {
  228. __i915_gem_object_release_shmem(obj, pages, false);
  229. if (obj->mm.dirty) {
  230. struct address_space *mapping = obj->base.filp->f_mapping;
  231. char *vaddr = obj->phys_handle->vaddr;
  232. int i;
  233. for (i = 0; i < obj->base.size / PAGE_SIZE; i++) {
  234. struct page *page;
  235. char *dst;
  236. page = shmem_read_mapping_page(mapping, i);
  237. if (IS_ERR(page))
  238. continue;
  239. dst = kmap_atomic(page);
  240. drm_clflush_virt_range(vaddr, PAGE_SIZE);
  241. memcpy(dst, vaddr, PAGE_SIZE);
  242. kunmap_atomic(dst);
  243. set_page_dirty(page);
  244. if (obj->mm.madv == I915_MADV_WILLNEED)
  245. mark_page_accessed(page);
  246. put_page(page);
  247. vaddr += PAGE_SIZE;
  248. }
  249. obj->mm.dirty = false;
  250. }
  251. sg_free_table(pages);
  252. kfree(pages);
  253. drm_pci_free(obj->base.dev, obj->phys_handle);
  254. }
  255. static void
  256. i915_gem_object_release_phys(struct drm_i915_gem_object *obj)
  257. {
  258. i915_gem_object_unpin_pages(obj);
  259. }
  260. static const struct drm_i915_gem_object_ops i915_gem_phys_ops = {
  261. .get_pages = i915_gem_object_get_pages_phys,
  262. .put_pages = i915_gem_object_put_pages_phys,
  263. .release = i915_gem_object_release_phys,
  264. };
  265. static const struct drm_i915_gem_object_ops i915_gem_object_ops;
  266. int i915_gem_object_unbind(struct drm_i915_gem_object *obj)
  267. {
  268. struct i915_vma *vma;
  269. LIST_HEAD(still_in_list);
  270. int ret;
  271. lockdep_assert_held(&obj->base.dev->struct_mutex);
  272. /* Closed vma are removed from the obj->vma_list - but they may
  273. * still have an active binding on the object. To remove those we
  274. * must wait for all rendering to complete to the object (as unbinding
  275. * must anyway), and retire the requests.
  276. */
  277. ret = i915_gem_object_set_to_cpu_domain(obj, false);
  278. if (ret)
  279. return ret;
  280. while ((vma = list_first_entry_or_null(&obj->vma_list,
  281. struct i915_vma,
  282. obj_link))) {
  283. list_move_tail(&vma->obj_link, &still_in_list);
  284. ret = i915_vma_unbind(vma);
  285. if (ret)
  286. break;
  287. }
  288. list_splice(&still_in_list, &obj->vma_list);
  289. return ret;
  290. }
  291. static long
  292. i915_gem_object_wait_fence(struct dma_fence *fence,
  293. unsigned int flags,
  294. long timeout,
  295. struct intel_rps_client *rps_client)
  296. {
  297. struct i915_request *rq;
  298. BUILD_BUG_ON(I915_WAIT_INTERRUPTIBLE != 0x1);
  299. if (test_bit(DMA_FENCE_FLAG_SIGNALED_BIT, &fence->flags))
  300. return timeout;
  301. if (!dma_fence_is_i915(fence))
  302. return dma_fence_wait_timeout(fence,
  303. flags & I915_WAIT_INTERRUPTIBLE,
  304. timeout);
  305. rq = to_request(fence);
  306. if (i915_request_completed(rq))
  307. goto out;
  308. /*
  309. * This client is about to stall waiting for the GPU. In many cases
  310. * this is undesirable and limits the throughput of the system, as
  311. * many clients cannot continue processing user input/output whilst
  312. * blocked. RPS autotuning may take tens of milliseconds to respond
  313. * to the GPU load and thus incurs additional latency for the client.
  314. * We can circumvent that by promoting the GPU frequency to maximum
  315. * before we wait. This makes the GPU throttle up much more quickly
  316. * (good for benchmarks and user experience, e.g. window animations),
  317. * but at a cost of spending more power processing the workload
  318. * (bad for battery). Not all clients even want their results
  319. * immediately and for them we should just let the GPU select its own
  320. * frequency to maximise efficiency. To prevent a single client from
  321. * forcing the clocks too high for the whole system, we only allow
  322. * each client to waitboost once in a busy period.
  323. */
  324. if (rps_client && !i915_request_started(rq)) {
  325. if (INTEL_GEN(rq->i915) >= 6)
  326. gen6_rps_boost(rq, rps_client);
  327. }
  328. timeout = i915_request_wait(rq, flags, timeout);
  329. out:
  330. if (flags & I915_WAIT_LOCKED && i915_request_completed(rq))
  331. i915_request_retire_upto(rq);
  332. return timeout;
  333. }
  334. static long
  335. i915_gem_object_wait_reservation(struct reservation_object *resv,
  336. unsigned int flags,
  337. long timeout,
  338. struct intel_rps_client *rps_client)
  339. {
  340. unsigned int seq = __read_seqcount_begin(&resv->seq);
  341. struct dma_fence *excl;
  342. bool prune_fences = false;
  343. if (flags & I915_WAIT_ALL) {
  344. struct dma_fence **shared;
  345. unsigned int count, i;
  346. int ret;
  347. ret = reservation_object_get_fences_rcu(resv,
  348. &excl, &count, &shared);
  349. if (ret)
  350. return ret;
  351. for (i = 0; i < count; i++) {
  352. timeout = i915_gem_object_wait_fence(shared[i],
  353. flags, timeout,
  354. rps_client);
  355. if (timeout < 0)
  356. break;
  357. dma_fence_put(shared[i]);
  358. }
  359. for (; i < count; i++)
  360. dma_fence_put(shared[i]);
  361. kfree(shared);
  362. /*
  363. * If both shared fences and an exclusive fence exist,
  364. * then by construction the shared fences must be later
  365. * than the exclusive fence. If we successfully wait for
  366. * all the shared fences, we know that the exclusive fence
  367. * must all be signaled. If all the shared fences are
  368. * signaled, we can prune the array and recover the
  369. * floating references on the fences/requests.
  370. */
  371. prune_fences = count && timeout >= 0;
  372. } else {
  373. excl = reservation_object_get_excl_rcu(resv);
  374. }
  375. if (excl && timeout >= 0)
  376. timeout = i915_gem_object_wait_fence(excl, flags, timeout,
  377. rps_client);
  378. dma_fence_put(excl);
  379. /*
  380. * Opportunistically prune the fences iff we know they have *all* been
  381. * signaled and that the reservation object has not been changed (i.e.
  382. * no new fences have been added).
  383. */
  384. if (prune_fences && !__read_seqcount_retry(&resv->seq, seq)) {
  385. if (reservation_object_trylock(resv)) {
  386. if (!__read_seqcount_retry(&resv->seq, seq))
  387. reservation_object_add_excl_fence(resv, NULL);
  388. reservation_object_unlock(resv);
  389. }
  390. }
  391. return timeout;
  392. }
  393. static void __fence_set_priority(struct dma_fence *fence, int prio)
  394. {
  395. struct i915_request *rq;
  396. struct intel_engine_cs *engine;
  397. if (dma_fence_is_signaled(fence) || !dma_fence_is_i915(fence))
  398. return;
  399. rq = to_request(fence);
  400. engine = rq->engine;
  401. rcu_read_lock();
  402. if (engine->schedule)
  403. engine->schedule(rq, prio);
  404. rcu_read_unlock();
  405. }
  406. static void fence_set_priority(struct dma_fence *fence, int prio)
  407. {
  408. /* Recurse once into a fence-array */
  409. if (dma_fence_is_array(fence)) {
  410. struct dma_fence_array *array = to_dma_fence_array(fence);
  411. int i;
  412. for (i = 0; i < array->num_fences; i++)
  413. __fence_set_priority(array->fences[i], prio);
  414. } else {
  415. __fence_set_priority(fence, prio);
  416. }
  417. }
  418. int
  419. i915_gem_object_wait_priority(struct drm_i915_gem_object *obj,
  420. unsigned int flags,
  421. int prio)
  422. {
  423. struct dma_fence *excl;
  424. if (flags & I915_WAIT_ALL) {
  425. struct dma_fence **shared;
  426. unsigned int count, i;
  427. int ret;
  428. ret = reservation_object_get_fences_rcu(obj->resv,
  429. &excl, &count, &shared);
  430. if (ret)
  431. return ret;
  432. for (i = 0; i < count; i++) {
  433. fence_set_priority(shared[i], prio);
  434. dma_fence_put(shared[i]);
  435. }
  436. kfree(shared);
  437. } else {
  438. excl = reservation_object_get_excl_rcu(obj->resv);
  439. }
  440. if (excl) {
  441. fence_set_priority(excl, prio);
  442. dma_fence_put(excl);
  443. }
  444. return 0;
  445. }
  446. /**
  447. * Waits for rendering to the object to be completed
  448. * @obj: i915 gem object
  449. * @flags: how to wait (under a lock, for all rendering or just for writes etc)
  450. * @timeout: how long to wait
  451. * @rps_client: client (user process) to charge for any waitboosting
  452. */
  453. int
  454. i915_gem_object_wait(struct drm_i915_gem_object *obj,
  455. unsigned int flags,
  456. long timeout,
  457. struct intel_rps_client *rps_client)
  458. {
  459. might_sleep();
  460. #if IS_ENABLED(CONFIG_LOCKDEP)
  461. GEM_BUG_ON(debug_locks &&
  462. !!lockdep_is_held(&obj->base.dev->struct_mutex) !=
  463. !!(flags & I915_WAIT_LOCKED));
  464. #endif
  465. GEM_BUG_ON(timeout < 0);
  466. timeout = i915_gem_object_wait_reservation(obj->resv,
  467. flags, timeout,
  468. rps_client);
  469. return timeout < 0 ? timeout : 0;
  470. }
  471. static struct intel_rps_client *to_rps_client(struct drm_file *file)
  472. {
  473. struct drm_i915_file_private *fpriv = file->driver_priv;
  474. return &fpriv->rps_client;
  475. }
  476. static int
  477. i915_gem_phys_pwrite(struct drm_i915_gem_object *obj,
  478. struct drm_i915_gem_pwrite *args,
  479. struct drm_file *file)
  480. {
  481. void *vaddr = obj->phys_handle->vaddr + args->offset;
  482. char __user *user_data = u64_to_user_ptr(args->data_ptr);
  483. /* We manually control the domain here and pretend that it
  484. * remains coherent i.e. in the GTT domain, like shmem_pwrite.
  485. */
  486. intel_fb_obj_invalidate(obj, ORIGIN_CPU);
  487. if (copy_from_user(vaddr, user_data, args->size))
  488. return -EFAULT;
  489. drm_clflush_virt_range(vaddr, args->size);
  490. i915_gem_chipset_flush(to_i915(obj->base.dev));
  491. intel_fb_obj_flush(obj, ORIGIN_CPU);
  492. return 0;
  493. }
  494. void *i915_gem_object_alloc(struct drm_i915_private *dev_priv)
  495. {
  496. return kmem_cache_zalloc(dev_priv->objects, GFP_KERNEL);
  497. }
  498. void i915_gem_object_free(struct drm_i915_gem_object *obj)
  499. {
  500. struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
  501. kmem_cache_free(dev_priv->objects, obj);
  502. }
  503. static int
  504. i915_gem_create(struct drm_file *file,
  505. struct drm_i915_private *dev_priv,
  506. uint64_t size,
  507. uint32_t *handle_p)
  508. {
  509. struct drm_i915_gem_object *obj;
  510. int ret;
  511. u32 handle;
  512. size = roundup(size, PAGE_SIZE);
  513. if (size == 0)
  514. return -EINVAL;
  515. /* Allocate the new object */
  516. obj = i915_gem_object_create(dev_priv, size);
  517. if (IS_ERR(obj))
  518. return PTR_ERR(obj);
  519. ret = drm_gem_handle_create(file, &obj->base, &handle);
  520. /* drop reference from allocate - handle holds it now */
  521. i915_gem_object_put(obj);
  522. if (ret)
  523. return ret;
  524. *handle_p = handle;
  525. return 0;
  526. }
  527. int
  528. i915_gem_dumb_create(struct drm_file *file,
  529. struct drm_device *dev,
  530. struct drm_mode_create_dumb *args)
  531. {
  532. /* have to work out size/pitch and return them */
  533. args->pitch = ALIGN(args->width * DIV_ROUND_UP(args->bpp, 8), 64);
  534. args->size = args->pitch * args->height;
  535. return i915_gem_create(file, to_i915(dev),
  536. args->size, &args->handle);
  537. }
  538. static bool gpu_write_needs_clflush(struct drm_i915_gem_object *obj)
  539. {
  540. return !(obj->cache_level == I915_CACHE_NONE ||
  541. obj->cache_level == I915_CACHE_WT);
  542. }
  543. /**
  544. * Creates a new mm object and returns a handle to it.
  545. * @dev: drm device pointer
  546. * @data: ioctl data blob
  547. * @file: drm file pointer
  548. */
  549. int
  550. i915_gem_create_ioctl(struct drm_device *dev, void *data,
  551. struct drm_file *file)
  552. {
  553. struct drm_i915_private *dev_priv = to_i915(dev);
  554. struct drm_i915_gem_create *args = data;
  555. i915_gem_flush_free_objects(dev_priv);
  556. return i915_gem_create(file, dev_priv,
  557. args->size, &args->handle);
  558. }
  559. static inline enum fb_op_origin
  560. fb_write_origin(struct drm_i915_gem_object *obj, unsigned int domain)
  561. {
  562. return (domain == I915_GEM_DOMAIN_GTT ?
  563. obj->frontbuffer_ggtt_origin : ORIGIN_CPU);
  564. }
  565. void i915_gem_flush_ggtt_writes(struct drm_i915_private *dev_priv)
  566. {
  567. /*
  568. * No actual flushing is required for the GTT write domain for reads
  569. * from the GTT domain. Writes to it "immediately" go to main memory
  570. * as far as we know, so there's no chipset flush. It also doesn't
  571. * land in the GPU render cache.
  572. *
  573. * However, we do have to enforce the order so that all writes through
  574. * the GTT land before any writes to the device, such as updates to
  575. * the GATT itself.
  576. *
  577. * We also have to wait a bit for the writes to land from the GTT.
  578. * An uncached read (i.e. mmio) seems to be ideal for the round-trip
  579. * timing. This issue has only been observed when switching quickly
  580. * between GTT writes and CPU reads from inside the kernel on recent hw,
  581. * and it appears to only affect discrete GTT blocks (i.e. on LLC
  582. * system agents we cannot reproduce this behaviour, until Cannonlake
  583. * that was!).
  584. */
  585. wmb();
  586. intel_runtime_pm_get(dev_priv);
  587. spin_lock_irq(&dev_priv->uncore.lock);
  588. POSTING_READ_FW(RING_HEAD(RENDER_RING_BASE));
  589. spin_unlock_irq(&dev_priv->uncore.lock);
  590. intel_runtime_pm_put(dev_priv);
  591. }
  592. static void
  593. flush_write_domain(struct drm_i915_gem_object *obj, unsigned int flush_domains)
  594. {
  595. struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
  596. struct i915_vma *vma;
  597. if (!(obj->write_domain & flush_domains))
  598. return;
  599. switch (obj->write_domain) {
  600. case I915_GEM_DOMAIN_GTT:
  601. i915_gem_flush_ggtt_writes(dev_priv);
  602. intel_fb_obj_flush(obj,
  603. fb_write_origin(obj, I915_GEM_DOMAIN_GTT));
  604. for_each_ggtt_vma(vma, obj) {
  605. if (vma->iomap)
  606. continue;
  607. i915_vma_unset_ggtt_write(vma);
  608. }
  609. break;
  610. case I915_GEM_DOMAIN_CPU:
  611. i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
  612. break;
  613. case I915_GEM_DOMAIN_RENDER:
  614. if (gpu_write_needs_clflush(obj))
  615. obj->cache_dirty = true;
  616. break;
  617. }
  618. obj->write_domain = 0;
  619. }
  620. static inline int
  621. __copy_to_user_swizzled(char __user *cpu_vaddr,
  622. const char *gpu_vaddr, int gpu_offset,
  623. int length)
  624. {
  625. int ret, cpu_offset = 0;
  626. while (length > 0) {
  627. int cacheline_end = ALIGN(gpu_offset + 1, 64);
  628. int this_length = min(cacheline_end - gpu_offset, length);
  629. int swizzled_gpu_offset = gpu_offset ^ 64;
  630. ret = __copy_to_user(cpu_vaddr + cpu_offset,
  631. gpu_vaddr + swizzled_gpu_offset,
  632. this_length);
  633. if (ret)
  634. return ret + length;
  635. cpu_offset += this_length;
  636. gpu_offset += this_length;
  637. length -= this_length;
  638. }
  639. return 0;
  640. }
  641. static inline int
  642. __copy_from_user_swizzled(char *gpu_vaddr, int gpu_offset,
  643. const char __user *cpu_vaddr,
  644. int length)
  645. {
  646. int ret, cpu_offset = 0;
  647. while (length > 0) {
  648. int cacheline_end = ALIGN(gpu_offset + 1, 64);
  649. int this_length = min(cacheline_end - gpu_offset, length);
  650. int swizzled_gpu_offset = gpu_offset ^ 64;
  651. ret = __copy_from_user(gpu_vaddr + swizzled_gpu_offset,
  652. cpu_vaddr + cpu_offset,
  653. this_length);
  654. if (ret)
  655. return ret + length;
  656. cpu_offset += this_length;
  657. gpu_offset += this_length;
  658. length -= this_length;
  659. }
  660. return 0;
  661. }
  662. /*
  663. * Pins the specified object's pages and synchronizes the object with
  664. * GPU accesses. Sets needs_clflush to non-zero if the caller should
  665. * flush the object from the CPU cache.
  666. */
  667. int i915_gem_obj_prepare_shmem_read(struct drm_i915_gem_object *obj,
  668. unsigned int *needs_clflush)
  669. {
  670. int ret;
  671. lockdep_assert_held(&obj->base.dev->struct_mutex);
  672. *needs_clflush = 0;
  673. if (!i915_gem_object_has_struct_page(obj))
  674. return -ENODEV;
  675. ret = i915_gem_object_wait(obj,
  676. I915_WAIT_INTERRUPTIBLE |
  677. I915_WAIT_LOCKED,
  678. MAX_SCHEDULE_TIMEOUT,
  679. NULL);
  680. if (ret)
  681. return ret;
  682. ret = i915_gem_object_pin_pages(obj);
  683. if (ret)
  684. return ret;
  685. if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_READ ||
  686. !static_cpu_has(X86_FEATURE_CLFLUSH)) {
  687. ret = i915_gem_object_set_to_cpu_domain(obj, false);
  688. if (ret)
  689. goto err_unpin;
  690. else
  691. goto out;
  692. }
  693. flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
  694. /* If we're not in the cpu read domain, set ourself into the gtt
  695. * read domain and manually flush cachelines (if required). This
  696. * optimizes for the case when the gpu will dirty the data
  697. * anyway again before the next pread happens.
  698. */
  699. if (!obj->cache_dirty &&
  700. !(obj->read_domains & I915_GEM_DOMAIN_CPU))
  701. *needs_clflush = CLFLUSH_BEFORE;
  702. out:
  703. /* return with the pages pinned */
  704. return 0;
  705. err_unpin:
  706. i915_gem_object_unpin_pages(obj);
  707. return ret;
  708. }
  709. int i915_gem_obj_prepare_shmem_write(struct drm_i915_gem_object *obj,
  710. unsigned int *needs_clflush)
  711. {
  712. int ret;
  713. lockdep_assert_held(&obj->base.dev->struct_mutex);
  714. *needs_clflush = 0;
  715. if (!i915_gem_object_has_struct_page(obj))
  716. return -ENODEV;
  717. ret = i915_gem_object_wait(obj,
  718. I915_WAIT_INTERRUPTIBLE |
  719. I915_WAIT_LOCKED |
  720. I915_WAIT_ALL,
  721. MAX_SCHEDULE_TIMEOUT,
  722. NULL);
  723. if (ret)
  724. return ret;
  725. ret = i915_gem_object_pin_pages(obj);
  726. if (ret)
  727. return ret;
  728. if (obj->cache_coherent & I915_BO_CACHE_COHERENT_FOR_WRITE ||
  729. !static_cpu_has(X86_FEATURE_CLFLUSH)) {
  730. ret = i915_gem_object_set_to_cpu_domain(obj, true);
  731. if (ret)
  732. goto err_unpin;
  733. else
  734. goto out;
  735. }
  736. flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
  737. /* If we're not in the cpu write domain, set ourself into the
  738. * gtt write domain and manually flush cachelines (as required).
  739. * This optimizes for the case when the gpu will use the data
  740. * right away and we therefore have to clflush anyway.
  741. */
  742. if (!obj->cache_dirty) {
  743. *needs_clflush |= CLFLUSH_AFTER;
  744. /*
  745. * Same trick applies to invalidate partially written
  746. * cachelines read before writing.
  747. */
  748. if (!(obj->read_domains & I915_GEM_DOMAIN_CPU))
  749. *needs_clflush |= CLFLUSH_BEFORE;
  750. }
  751. out:
  752. intel_fb_obj_invalidate(obj, ORIGIN_CPU);
  753. obj->mm.dirty = true;
  754. /* return with the pages pinned */
  755. return 0;
  756. err_unpin:
  757. i915_gem_object_unpin_pages(obj);
  758. return ret;
  759. }
  760. static void
  761. shmem_clflush_swizzled_range(char *addr, unsigned long length,
  762. bool swizzled)
  763. {
  764. if (unlikely(swizzled)) {
  765. unsigned long start = (unsigned long) addr;
  766. unsigned long end = (unsigned long) addr + length;
  767. /* For swizzling simply ensure that we always flush both
  768. * channels. Lame, but simple and it works. Swizzled
  769. * pwrite/pread is far from a hotpath - current userspace
  770. * doesn't use it at all. */
  771. start = round_down(start, 128);
  772. end = round_up(end, 128);
  773. drm_clflush_virt_range((void *)start, end - start);
  774. } else {
  775. drm_clflush_virt_range(addr, length);
  776. }
  777. }
  778. /* Only difference to the fast-path function is that this can handle bit17
  779. * and uses non-atomic copy and kmap functions. */
  780. static int
  781. shmem_pread_slow(struct page *page, int offset, int length,
  782. char __user *user_data,
  783. bool page_do_bit17_swizzling, bool needs_clflush)
  784. {
  785. char *vaddr;
  786. int ret;
  787. vaddr = kmap(page);
  788. if (needs_clflush)
  789. shmem_clflush_swizzled_range(vaddr + offset, length,
  790. page_do_bit17_swizzling);
  791. if (page_do_bit17_swizzling)
  792. ret = __copy_to_user_swizzled(user_data, vaddr, offset, length);
  793. else
  794. ret = __copy_to_user(user_data, vaddr + offset, length);
  795. kunmap(page);
  796. return ret ? - EFAULT : 0;
  797. }
  798. static int
  799. shmem_pread(struct page *page, int offset, int length, char __user *user_data,
  800. bool page_do_bit17_swizzling, bool needs_clflush)
  801. {
  802. int ret;
  803. ret = -ENODEV;
  804. if (!page_do_bit17_swizzling) {
  805. char *vaddr = kmap_atomic(page);
  806. if (needs_clflush)
  807. drm_clflush_virt_range(vaddr + offset, length);
  808. ret = __copy_to_user_inatomic(user_data, vaddr + offset, length);
  809. kunmap_atomic(vaddr);
  810. }
  811. if (ret == 0)
  812. return 0;
  813. return shmem_pread_slow(page, offset, length, user_data,
  814. page_do_bit17_swizzling, needs_clflush);
  815. }
  816. static int
  817. i915_gem_shmem_pread(struct drm_i915_gem_object *obj,
  818. struct drm_i915_gem_pread *args)
  819. {
  820. char __user *user_data;
  821. u64 remain;
  822. unsigned int obj_do_bit17_swizzling;
  823. unsigned int needs_clflush;
  824. unsigned int idx, offset;
  825. int ret;
  826. obj_do_bit17_swizzling = 0;
  827. if (i915_gem_object_needs_bit17_swizzle(obj))
  828. obj_do_bit17_swizzling = BIT(17);
  829. ret = mutex_lock_interruptible(&obj->base.dev->struct_mutex);
  830. if (ret)
  831. return ret;
  832. ret = i915_gem_obj_prepare_shmem_read(obj, &needs_clflush);
  833. mutex_unlock(&obj->base.dev->struct_mutex);
  834. if (ret)
  835. return ret;
  836. remain = args->size;
  837. user_data = u64_to_user_ptr(args->data_ptr);
  838. offset = offset_in_page(args->offset);
  839. for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
  840. struct page *page = i915_gem_object_get_page(obj, idx);
  841. int length;
  842. length = remain;
  843. if (offset + length > PAGE_SIZE)
  844. length = PAGE_SIZE - offset;
  845. ret = shmem_pread(page, offset, length, user_data,
  846. page_to_phys(page) & obj_do_bit17_swizzling,
  847. needs_clflush);
  848. if (ret)
  849. break;
  850. remain -= length;
  851. user_data += length;
  852. offset = 0;
  853. }
  854. i915_gem_obj_finish_shmem_access(obj);
  855. return ret;
  856. }
  857. static inline bool
  858. gtt_user_read(struct io_mapping *mapping,
  859. loff_t base, int offset,
  860. char __user *user_data, int length)
  861. {
  862. void __iomem *vaddr;
  863. unsigned long unwritten;
  864. /* We can use the cpu mem copy function because this is X86. */
  865. vaddr = io_mapping_map_atomic_wc(mapping, base);
  866. unwritten = __copy_to_user_inatomic(user_data,
  867. (void __force *)vaddr + offset,
  868. length);
  869. io_mapping_unmap_atomic(vaddr);
  870. if (unwritten) {
  871. vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
  872. unwritten = copy_to_user(user_data,
  873. (void __force *)vaddr + offset,
  874. length);
  875. io_mapping_unmap(vaddr);
  876. }
  877. return unwritten;
  878. }
  879. static int
  880. i915_gem_gtt_pread(struct drm_i915_gem_object *obj,
  881. const struct drm_i915_gem_pread *args)
  882. {
  883. struct drm_i915_private *i915 = to_i915(obj->base.dev);
  884. struct i915_ggtt *ggtt = &i915->ggtt;
  885. struct drm_mm_node node;
  886. struct i915_vma *vma;
  887. void __user *user_data;
  888. u64 remain, offset;
  889. int ret;
  890. ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
  891. if (ret)
  892. return ret;
  893. intel_runtime_pm_get(i915);
  894. vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
  895. PIN_MAPPABLE |
  896. PIN_NONFAULT |
  897. PIN_NONBLOCK);
  898. if (!IS_ERR(vma)) {
  899. node.start = i915_ggtt_offset(vma);
  900. node.allocated = false;
  901. ret = i915_vma_put_fence(vma);
  902. if (ret) {
  903. i915_vma_unpin(vma);
  904. vma = ERR_PTR(ret);
  905. }
  906. }
  907. if (IS_ERR(vma)) {
  908. ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
  909. if (ret)
  910. goto out_unlock;
  911. GEM_BUG_ON(!node.allocated);
  912. }
  913. ret = i915_gem_object_set_to_gtt_domain(obj, false);
  914. if (ret)
  915. goto out_unpin;
  916. mutex_unlock(&i915->drm.struct_mutex);
  917. user_data = u64_to_user_ptr(args->data_ptr);
  918. remain = args->size;
  919. offset = args->offset;
  920. while (remain > 0) {
  921. /* Operation in this page
  922. *
  923. * page_base = page offset within aperture
  924. * page_offset = offset within page
  925. * page_length = bytes to copy for this page
  926. */
  927. u32 page_base = node.start;
  928. unsigned page_offset = offset_in_page(offset);
  929. unsigned page_length = PAGE_SIZE - page_offset;
  930. page_length = remain < page_length ? remain : page_length;
  931. if (node.allocated) {
  932. wmb();
  933. ggtt->base.insert_page(&ggtt->base,
  934. i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
  935. node.start, I915_CACHE_NONE, 0);
  936. wmb();
  937. } else {
  938. page_base += offset & PAGE_MASK;
  939. }
  940. if (gtt_user_read(&ggtt->iomap, page_base, page_offset,
  941. user_data, page_length)) {
  942. ret = -EFAULT;
  943. break;
  944. }
  945. remain -= page_length;
  946. user_data += page_length;
  947. offset += page_length;
  948. }
  949. mutex_lock(&i915->drm.struct_mutex);
  950. out_unpin:
  951. if (node.allocated) {
  952. wmb();
  953. ggtt->base.clear_range(&ggtt->base,
  954. node.start, node.size);
  955. remove_mappable_node(&node);
  956. } else {
  957. i915_vma_unpin(vma);
  958. }
  959. out_unlock:
  960. intel_runtime_pm_put(i915);
  961. mutex_unlock(&i915->drm.struct_mutex);
  962. return ret;
  963. }
  964. /**
  965. * Reads data from the object referenced by handle.
  966. * @dev: drm device pointer
  967. * @data: ioctl data blob
  968. * @file: drm file pointer
  969. *
  970. * On error, the contents of *data are undefined.
  971. */
  972. int
  973. i915_gem_pread_ioctl(struct drm_device *dev, void *data,
  974. struct drm_file *file)
  975. {
  976. struct drm_i915_gem_pread *args = data;
  977. struct drm_i915_gem_object *obj;
  978. int ret;
  979. if (args->size == 0)
  980. return 0;
  981. if (!access_ok(VERIFY_WRITE,
  982. u64_to_user_ptr(args->data_ptr),
  983. args->size))
  984. return -EFAULT;
  985. obj = i915_gem_object_lookup(file, args->handle);
  986. if (!obj)
  987. return -ENOENT;
  988. /* Bounds check source. */
  989. if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
  990. ret = -EINVAL;
  991. goto out;
  992. }
  993. trace_i915_gem_object_pread(obj, args->offset, args->size);
  994. ret = i915_gem_object_wait(obj,
  995. I915_WAIT_INTERRUPTIBLE,
  996. MAX_SCHEDULE_TIMEOUT,
  997. to_rps_client(file));
  998. if (ret)
  999. goto out;
  1000. ret = i915_gem_object_pin_pages(obj);
  1001. if (ret)
  1002. goto out;
  1003. ret = i915_gem_shmem_pread(obj, args);
  1004. if (ret == -EFAULT || ret == -ENODEV)
  1005. ret = i915_gem_gtt_pread(obj, args);
  1006. i915_gem_object_unpin_pages(obj);
  1007. out:
  1008. i915_gem_object_put(obj);
  1009. return ret;
  1010. }
  1011. /* This is the fast write path which cannot handle
  1012. * page faults in the source data
  1013. */
  1014. static inline bool
  1015. ggtt_write(struct io_mapping *mapping,
  1016. loff_t base, int offset,
  1017. char __user *user_data, int length)
  1018. {
  1019. void __iomem *vaddr;
  1020. unsigned long unwritten;
  1021. /* We can use the cpu mem copy function because this is X86. */
  1022. vaddr = io_mapping_map_atomic_wc(mapping, base);
  1023. unwritten = __copy_from_user_inatomic_nocache((void __force *)vaddr + offset,
  1024. user_data, length);
  1025. io_mapping_unmap_atomic(vaddr);
  1026. if (unwritten) {
  1027. vaddr = io_mapping_map_wc(mapping, base, PAGE_SIZE);
  1028. unwritten = copy_from_user((void __force *)vaddr + offset,
  1029. user_data, length);
  1030. io_mapping_unmap(vaddr);
  1031. }
  1032. return unwritten;
  1033. }
  1034. /**
  1035. * This is the fast pwrite path, where we copy the data directly from the
  1036. * user into the GTT, uncached.
  1037. * @obj: i915 GEM object
  1038. * @args: pwrite arguments structure
  1039. */
  1040. static int
  1041. i915_gem_gtt_pwrite_fast(struct drm_i915_gem_object *obj,
  1042. const struct drm_i915_gem_pwrite *args)
  1043. {
  1044. struct drm_i915_private *i915 = to_i915(obj->base.dev);
  1045. struct i915_ggtt *ggtt = &i915->ggtt;
  1046. struct drm_mm_node node;
  1047. struct i915_vma *vma;
  1048. u64 remain, offset;
  1049. void __user *user_data;
  1050. int ret;
  1051. ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
  1052. if (ret)
  1053. return ret;
  1054. if (i915_gem_object_has_struct_page(obj)) {
  1055. /*
  1056. * Avoid waking the device up if we can fallback, as
  1057. * waking/resuming is very slow (worst-case 10-100 ms
  1058. * depending on PCI sleeps and our own resume time).
  1059. * This easily dwarfs any performance advantage from
  1060. * using the cache bypass of indirect GGTT access.
  1061. */
  1062. if (!intel_runtime_pm_get_if_in_use(i915)) {
  1063. ret = -EFAULT;
  1064. goto out_unlock;
  1065. }
  1066. } else {
  1067. /* No backing pages, no fallback, we must force GGTT access */
  1068. intel_runtime_pm_get(i915);
  1069. }
  1070. vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0,
  1071. PIN_MAPPABLE |
  1072. PIN_NONFAULT |
  1073. PIN_NONBLOCK);
  1074. if (!IS_ERR(vma)) {
  1075. node.start = i915_ggtt_offset(vma);
  1076. node.allocated = false;
  1077. ret = i915_vma_put_fence(vma);
  1078. if (ret) {
  1079. i915_vma_unpin(vma);
  1080. vma = ERR_PTR(ret);
  1081. }
  1082. }
  1083. if (IS_ERR(vma)) {
  1084. ret = insert_mappable_node(ggtt, &node, PAGE_SIZE);
  1085. if (ret)
  1086. goto out_rpm;
  1087. GEM_BUG_ON(!node.allocated);
  1088. }
  1089. ret = i915_gem_object_set_to_gtt_domain(obj, true);
  1090. if (ret)
  1091. goto out_unpin;
  1092. mutex_unlock(&i915->drm.struct_mutex);
  1093. intel_fb_obj_invalidate(obj, ORIGIN_CPU);
  1094. user_data = u64_to_user_ptr(args->data_ptr);
  1095. offset = args->offset;
  1096. remain = args->size;
  1097. while (remain) {
  1098. /* Operation in this page
  1099. *
  1100. * page_base = page offset within aperture
  1101. * page_offset = offset within page
  1102. * page_length = bytes to copy for this page
  1103. */
  1104. u32 page_base = node.start;
  1105. unsigned int page_offset = offset_in_page(offset);
  1106. unsigned int page_length = PAGE_SIZE - page_offset;
  1107. page_length = remain < page_length ? remain : page_length;
  1108. if (node.allocated) {
  1109. wmb(); /* flush the write before we modify the GGTT */
  1110. ggtt->base.insert_page(&ggtt->base,
  1111. i915_gem_object_get_dma_address(obj, offset >> PAGE_SHIFT),
  1112. node.start, I915_CACHE_NONE, 0);
  1113. wmb(); /* flush modifications to the GGTT (insert_page) */
  1114. } else {
  1115. page_base += offset & PAGE_MASK;
  1116. }
  1117. /* If we get a fault while copying data, then (presumably) our
  1118. * source page isn't available. Return the error and we'll
  1119. * retry in the slow path.
  1120. * If the object is non-shmem backed, we retry again with the
  1121. * path that handles page fault.
  1122. */
  1123. if (ggtt_write(&ggtt->iomap, page_base, page_offset,
  1124. user_data, page_length)) {
  1125. ret = -EFAULT;
  1126. break;
  1127. }
  1128. remain -= page_length;
  1129. user_data += page_length;
  1130. offset += page_length;
  1131. }
  1132. intel_fb_obj_flush(obj, ORIGIN_CPU);
  1133. mutex_lock(&i915->drm.struct_mutex);
  1134. out_unpin:
  1135. if (node.allocated) {
  1136. wmb();
  1137. ggtt->base.clear_range(&ggtt->base,
  1138. node.start, node.size);
  1139. remove_mappable_node(&node);
  1140. } else {
  1141. i915_vma_unpin(vma);
  1142. }
  1143. out_rpm:
  1144. intel_runtime_pm_put(i915);
  1145. out_unlock:
  1146. mutex_unlock(&i915->drm.struct_mutex);
  1147. return ret;
  1148. }
  1149. static int
  1150. shmem_pwrite_slow(struct page *page, int offset, int length,
  1151. char __user *user_data,
  1152. bool page_do_bit17_swizzling,
  1153. bool needs_clflush_before,
  1154. bool needs_clflush_after)
  1155. {
  1156. char *vaddr;
  1157. int ret;
  1158. vaddr = kmap(page);
  1159. if (unlikely(needs_clflush_before || page_do_bit17_swizzling))
  1160. shmem_clflush_swizzled_range(vaddr + offset, length,
  1161. page_do_bit17_swizzling);
  1162. if (page_do_bit17_swizzling)
  1163. ret = __copy_from_user_swizzled(vaddr, offset, user_data,
  1164. length);
  1165. else
  1166. ret = __copy_from_user(vaddr + offset, user_data, length);
  1167. if (needs_clflush_after)
  1168. shmem_clflush_swizzled_range(vaddr + offset, length,
  1169. page_do_bit17_swizzling);
  1170. kunmap(page);
  1171. return ret ? -EFAULT : 0;
  1172. }
  1173. /* Per-page copy function for the shmem pwrite fastpath.
  1174. * Flushes invalid cachelines before writing to the target if
  1175. * needs_clflush_before is set and flushes out any written cachelines after
  1176. * writing if needs_clflush is set.
  1177. */
  1178. static int
  1179. shmem_pwrite(struct page *page, int offset, int len, char __user *user_data,
  1180. bool page_do_bit17_swizzling,
  1181. bool needs_clflush_before,
  1182. bool needs_clflush_after)
  1183. {
  1184. int ret;
  1185. ret = -ENODEV;
  1186. if (!page_do_bit17_swizzling) {
  1187. char *vaddr = kmap_atomic(page);
  1188. if (needs_clflush_before)
  1189. drm_clflush_virt_range(vaddr + offset, len);
  1190. ret = __copy_from_user_inatomic(vaddr + offset, user_data, len);
  1191. if (needs_clflush_after)
  1192. drm_clflush_virt_range(vaddr + offset, len);
  1193. kunmap_atomic(vaddr);
  1194. }
  1195. if (ret == 0)
  1196. return ret;
  1197. return shmem_pwrite_slow(page, offset, len, user_data,
  1198. page_do_bit17_swizzling,
  1199. needs_clflush_before,
  1200. needs_clflush_after);
  1201. }
  1202. static int
  1203. i915_gem_shmem_pwrite(struct drm_i915_gem_object *obj,
  1204. const struct drm_i915_gem_pwrite *args)
  1205. {
  1206. struct drm_i915_private *i915 = to_i915(obj->base.dev);
  1207. void __user *user_data;
  1208. u64 remain;
  1209. unsigned int obj_do_bit17_swizzling;
  1210. unsigned int partial_cacheline_write;
  1211. unsigned int needs_clflush;
  1212. unsigned int offset, idx;
  1213. int ret;
  1214. ret = mutex_lock_interruptible(&i915->drm.struct_mutex);
  1215. if (ret)
  1216. return ret;
  1217. ret = i915_gem_obj_prepare_shmem_write(obj, &needs_clflush);
  1218. mutex_unlock(&i915->drm.struct_mutex);
  1219. if (ret)
  1220. return ret;
  1221. obj_do_bit17_swizzling = 0;
  1222. if (i915_gem_object_needs_bit17_swizzle(obj))
  1223. obj_do_bit17_swizzling = BIT(17);
  1224. /* If we don't overwrite a cacheline completely we need to be
  1225. * careful to have up-to-date data by first clflushing. Don't
  1226. * overcomplicate things and flush the entire patch.
  1227. */
  1228. partial_cacheline_write = 0;
  1229. if (needs_clflush & CLFLUSH_BEFORE)
  1230. partial_cacheline_write = boot_cpu_data.x86_clflush_size - 1;
  1231. user_data = u64_to_user_ptr(args->data_ptr);
  1232. remain = args->size;
  1233. offset = offset_in_page(args->offset);
  1234. for (idx = args->offset >> PAGE_SHIFT; remain; idx++) {
  1235. struct page *page = i915_gem_object_get_page(obj, idx);
  1236. int length;
  1237. length = remain;
  1238. if (offset + length > PAGE_SIZE)
  1239. length = PAGE_SIZE - offset;
  1240. ret = shmem_pwrite(page, offset, length, user_data,
  1241. page_to_phys(page) & obj_do_bit17_swizzling,
  1242. (offset | length) & partial_cacheline_write,
  1243. needs_clflush & CLFLUSH_AFTER);
  1244. if (ret)
  1245. break;
  1246. remain -= length;
  1247. user_data += length;
  1248. offset = 0;
  1249. }
  1250. intel_fb_obj_flush(obj, ORIGIN_CPU);
  1251. i915_gem_obj_finish_shmem_access(obj);
  1252. return ret;
  1253. }
  1254. /**
  1255. * Writes data to the object referenced by handle.
  1256. * @dev: drm device
  1257. * @data: ioctl data blob
  1258. * @file: drm file
  1259. *
  1260. * On error, the contents of the buffer that were to be modified are undefined.
  1261. */
  1262. int
  1263. i915_gem_pwrite_ioctl(struct drm_device *dev, void *data,
  1264. struct drm_file *file)
  1265. {
  1266. struct drm_i915_gem_pwrite *args = data;
  1267. struct drm_i915_gem_object *obj;
  1268. int ret;
  1269. if (args->size == 0)
  1270. return 0;
  1271. if (!access_ok(VERIFY_READ,
  1272. u64_to_user_ptr(args->data_ptr),
  1273. args->size))
  1274. return -EFAULT;
  1275. obj = i915_gem_object_lookup(file, args->handle);
  1276. if (!obj)
  1277. return -ENOENT;
  1278. /* Bounds check destination. */
  1279. if (range_overflows_t(u64, args->offset, args->size, obj->base.size)) {
  1280. ret = -EINVAL;
  1281. goto err;
  1282. }
  1283. trace_i915_gem_object_pwrite(obj, args->offset, args->size);
  1284. ret = -ENODEV;
  1285. if (obj->ops->pwrite)
  1286. ret = obj->ops->pwrite(obj, args);
  1287. if (ret != -ENODEV)
  1288. goto err;
  1289. ret = i915_gem_object_wait(obj,
  1290. I915_WAIT_INTERRUPTIBLE |
  1291. I915_WAIT_ALL,
  1292. MAX_SCHEDULE_TIMEOUT,
  1293. to_rps_client(file));
  1294. if (ret)
  1295. goto err;
  1296. ret = i915_gem_object_pin_pages(obj);
  1297. if (ret)
  1298. goto err;
  1299. ret = -EFAULT;
  1300. /* We can only do the GTT pwrite on untiled buffers, as otherwise
  1301. * it would end up going through the fenced access, and we'll get
  1302. * different detiling behavior between reading and writing.
  1303. * pread/pwrite currently are reading and writing from the CPU
  1304. * perspective, requiring manual detiling by the client.
  1305. */
  1306. if (!i915_gem_object_has_struct_page(obj) ||
  1307. cpu_write_needs_clflush(obj))
  1308. /* Note that the gtt paths might fail with non-page-backed user
  1309. * pointers (e.g. gtt mappings when moving data between
  1310. * textures). Fallback to the shmem path in that case.
  1311. */
  1312. ret = i915_gem_gtt_pwrite_fast(obj, args);
  1313. if (ret == -EFAULT || ret == -ENOSPC) {
  1314. if (obj->phys_handle)
  1315. ret = i915_gem_phys_pwrite(obj, args, file);
  1316. else
  1317. ret = i915_gem_shmem_pwrite(obj, args);
  1318. }
  1319. i915_gem_object_unpin_pages(obj);
  1320. err:
  1321. i915_gem_object_put(obj);
  1322. return ret;
  1323. }
  1324. static void i915_gem_object_bump_inactive_ggtt(struct drm_i915_gem_object *obj)
  1325. {
  1326. struct drm_i915_private *i915;
  1327. struct list_head *list;
  1328. struct i915_vma *vma;
  1329. GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
  1330. for_each_ggtt_vma(vma, obj) {
  1331. if (i915_vma_is_active(vma))
  1332. continue;
  1333. if (!drm_mm_node_allocated(&vma->node))
  1334. continue;
  1335. list_move_tail(&vma->vm_link, &vma->vm->inactive_list);
  1336. }
  1337. i915 = to_i915(obj->base.dev);
  1338. spin_lock(&i915->mm.obj_lock);
  1339. list = obj->bind_count ? &i915->mm.bound_list : &i915->mm.unbound_list;
  1340. list_move_tail(&obj->mm.link, list);
  1341. spin_unlock(&i915->mm.obj_lock);
  1342. }
  1343. /**
  1344. * Called when user space prepares to use an object with the CPU, either
  1345. * through the mmap ioctl's mapping or a GTT mapping.
  1346. * @dev: drm device
  1347. * @data: ioctl data blob
  1348. * @file: drm file
  1349. */
  1350. int
  1351. i915_gem_set_domain_ioctl(struct drm_device *dev, void *data,
  1352. struct drm_file *file)
  1353. {
  1354. struct drm_i915_gem_set_domain *args = data;
  1355. struct drm_i915_gem_object *obj;
  1356. uint32_t read_domains = args->read_domains;
  1357. uint32_t write_domain = args->write_domain;
  1358. int err;
  1359. /* Only handle setting domains to types used by the CPU. */
  1360. if ((write_domain | read_domains) & I915_GEM_GPU_DOMAINS)
  1361. return -EINVAL;
  1362. /* Having something in the write domain implies it's in the read
  1363. * domain, and only that read domain. Enforce that in the request.
  1364. */
  1365. if (write_domain != 0 && read_domains != write_domain)
  1366. return -EINVAL;
  1367. obj = i915_gem_object_lookup(file, args->handle);
  1368. if (!obj)
  1369. return -ENOENT;
  1370. /* Try to flush the object off the GPU without holding the lock.
  1371. * We will repeat the flush holding the lock in the normal manner
  1372. * to catch cases where we are gazumped.
  1373. */
  1374. err = i915_gem_object_wait(obj,
  1375. I915_WAIT_INTERRUPTIBLE |
  1376. (write_domain ? I915_WAIT_ALL : 0),
  1377. MAX_SCHEDULE_TIMEOUT,
  1378. to_rps_client(file));
  1379. if (err)
  1380. goto out;
  1381. /*
  1382. * Proxy objects do not control access to the backing storage, ergo
  1383. * they cannot be used as a means to manipulate the cache domain
  1384. * tracking for that backing storage. The proxy object is always
  1385. * considered to be outside of any cache domain.
  1386. */
  1387. if (i915_gem_object_is_proxy(obj)) {
  1388. err = -ENXIO;
  1389. goto out;
  1390. }
  1391. /*
  1392. * Flush and acquire obj->pages so that we are coherent through
  1393. * direct access in memory with previous cached writes through
  1394. * shmemfs and that our cache domain tracking remains valid.
  1395. * For example, if the obj->filp was moved to swap without us
  1396. * being notified and releasing the pages, we would mistakenly
  1397. * continue to assume that the obj remained out of the CPU cached
  1398. * domain.
  1399. */
  1400. err = i915_gem_object_pin_pages(obj);
  1401. if (err)
  1402. goto out;
  1403. err = i915_mutex_lock_interruptible(dev);
  1404. if (err)
  1405. goto out_unpin;
  1406. if (read_domains & I915_GEM_DOMAIN_WC)
  1407. err = i915_gem_object_set_to_wc_domain(obj, write_domain);
  1408. else if (read_domains & I915_GEM_DOMAIN_GTT)
  1409. err = i915_gem_object_set_to_gtt_domain(obj, write_domain);
  1410. else
  1411. err = i915_gem_object_set_to_cpu_domain(obj, write_domain);
  1412. /* And bump the LRU for this access */
  1413. i915_gem_object_bump_inactive_ggtt(obj);
  1414. mutex_unlock(&dev->struct_mutex);
  1415. if (write_domain != 0)
  1416. intel_fb_obj_invalidate(obj,
  1417. fb_write_origin(obj, write_domain));
  1418. out_unpin:
  1419. i915_gem_object_unpin_pages(obj);
  1420. out:
  1421. i915_gem_object_put(obj);
  1422. return err;
  1423. }
  1424. /**
  1425. * Called when user space has done writes to this buffer
  1426. * @dev: drm device
  1427. * @data: ioctl data blob
  1428. * @file: drm file
  1429. */
  1430. int
  1431. i915_gem_sw_finish_ioctl(struct drm_device *dev, void *data,
  1432. struct drm_file *file)
  1433. {
  1434. struct drm_i915_gem_sw_finish *args = data;
  1435. struct drm_i915_gem_object *obj;
  1436. obj = i915_gem_object_lookup(file, args->handle);
  1437. if (!obj)
  1438. return -ENOENT;
  1439. /*
  1440. * Proxy objects are barred from CPU access, so there is no
  1441. * need to ban sw_finish as it is a nop.
  1442. */
  1443. /* Pinned buffers may be scanout, so flush the cache */
  1444. i915_gem_object_flush_if_display(obj);
  1445. i915_gem_object_put(obj);
  1446. return 0;
  1447. }
  1448. /**
  1449. * i915_gem_mmap_ioctl - Maps the contents of an object, returning the address
  1450. * it is mapped to.
  1451. * @dev: drm device
  1452. * @data: ioctl data blob
  1453. * @file: drm file
  1454. *
  1455. * While the mapping holds a reference on the contents of the object, it doesn't
  1456. * imply a ref on the object itself.
  1457. *
  1458. * IMPORTANT:
  1459. *
  1460. * DRM driver writers who look a this function as an example for how to do GEM
  1461. * mmap support, please don't implement mmap support like here. The modern way
  1462. * to implement DRM mmap support is with an mmap offset ioctl (like
  1463. * i915_gem_mmap_gtt) and then using the mmap syscall on the DRM fd directly.
  1464. * That way debug tooling like valgrind will understand what's going on, hiding
  1465. * the mmap call in a driver private ioctl will break that. The i915 driver only
  1466. * does cpu mmaps this way because we didn't know better.
  1467. */
  1468. int
  1469. i915_gem_mmap_ioctl(struct drm_device *dev, void *data,
  1470. struct drm_file *file)
  1471. {
  1472. struct drm_i915_gem_mmap *args = data;
  1473. struct drm_i915_gem_object *obj;
  1474. unsigned long addr;
  1475. if (args->flags & ~(I915_MMAP_WC))
  1476. return -EINVAL;
  1477. if (args->flags & I915_MMAP_WC && !boot_cpu_has(X86_FEATURE_PAT))
  1478. return -ENODEV;
  1479. obj = i915_gem_object_lookup(file, args->handle);
  1480. if (!obj)
  1481. return -ENOENT;
  1482. /* prime objects have no backing filp to GEM mmap
  1483. * pages from.
  1484. */
  1485. if (!obj->base.filp) {
  1486. i915_gem_object_put(obj);
  1487. return -ENXIO;
  1488. }
  1489. addr = vm_mmap(obj->base.filp, 0, args->size,
  1490. PROT_READ | PROT_WRITE, MAP_SHARED,
  1491. args->offset);
  1492. if (args->flags & I915_MMAP_WC) {
  1493. struct mm_struct *mm = current->mm;
  1494. struct vm_area_struct *vma;
  1495. if (down_write_killable(&mm->mmap_sem)) {
  1496. i915_gem_object_put(obj);
  1497. return -EINTR;
  1498. }
  1499. vma = find_vma(mm, addr);
  1500. if (vma)
  1501. vma->vm_page_prot =
  1502. pgprot_writecombine(vm_get_page_prot(vma->vm_flags));
  1503. else
  1504. addr = -ENOMEM;
  1505. up_write(&mm->mmap_sem);
  1506. /* This may race, but that's ok, it only gets set */
  1507. WRITE_ONCE(obj->frontbuffer_ggtt_origin, ORIGIN_CPU);
  1508. }
  1509. i915_gem_object_put(obj);
  1510. if (IS_ERR((void *)addr))
  1511. return addr;
  1512. args->addr_ptr = (uint64_t) addr;
  1513. return 0;
  1514. }
  1515. static unsigned int tile_row_pages(struct drm_i915_gem_object *obj)
  1516. {
  1517. return i915_gem_object_get_tile_row_size(obj) >> PAGE_SHIFT;
  1518. }
  1519. /**
  1520. * i915_gem_mmap_gtt_version - report the current feature set for GTT mmaps
  1521. *
  1522. * A history of the GTT mmap interface:
  1523. *
  1524. * 0 - Everything had to fit into the GTT. Both parties of a memcpy had to
  1525. * aligned and suitable for fencing, and still fit into the available
  1526. * mappable space left by the pinned display objects. A classic problem
  1527. * we called the page-fault-of-doom where we would ping-pong between
  1528. * two objects that could not fit inside the GTT and so the memcpy
  1529. * would page one object in at the expense of the other between every
  1530. * single byte.
  1531. *
  1532. * 1 - Objects can be any size, and have any compatible fencing (X Y, or none
  1533. * as set via i915_gem_set_tiling() [DRM_I915_GEM_SET_TILING]). If the
  1534. * object is too large for the available space (or simply too large
  1535. * for the mappable aperture!), a view is created instead and faulted
  1536. * into userspace. (This view is aligned and sized appropriately for
  1537. * fenced access.)
  1538. *
  1539. * 2 - Recognise WC as a separate cache domain so that we can flush the
  1540. * delayed writes via GTT before performing direct access via WC.
  1541. *
  1542. * Restrictions:
  1543. *
  1544. * * snoopable objects cannot be accessed via the GTT. It can cause machine
  1545. * hangs on some architectures, corruption on others. An attempt to service
  1546. * a GTT page fault from a snoopable object will generate a SIGBUS.
  1547. *
  1548. * * the object must be able to fit into RAM (physical memory, though no
  1549. * limited to the mappable aperture).
  1550. *
  1551. *
  1552. * Caveats:
  1553. *
  1554. * * a new GTT page fault will synchronize rendering from the GPU and flush
  1555. * all data to system memory. Subsequent access will not be synchronized.
  1556. *
  1557. * * all mappings are revoked on runtime device suspend.
  1558. *
  1559. * * there are only 8, 16 or 32 fence registers to share between all users
  1560. * (older machines require fence register for display and blitter access
  1561. * as well). Contention of the fence registers will cause the previous users
  1562. * to be unmapped and any new access will generate new page faults.
  1563. *
  1564. * * running out of memory while servicing a fault may generate a SIGBUS,
  1565. * rather than the expected SIGSEGV.
  1566. */
  1567. int i915_gem_mmap_gtt_version(void)
  1568. {
  1569. return 2;
  1570. }
  1571. static inline struct i915_ggtt_view
  1572. compute_partial_view(struct drm_i915_gem_object *obj,
  1573. pgoff_t page_offset,
  1574. unsigned int chunk)
  1575. {
  1576. struct i915_ggtt_view view;
  1577. if (i915_gem_object_is_tiled(obj))
  1578. chunk = roundup(chunk, tile_row_pages(obj));
  1579. view.type = I915_GGTT_VIEW_PARTIAL;
  1580. view.partial.offset = rounddown(page_offset, chunk);
  1581. view.partial.size =
  1582. min_t(unsigned int, chunk,
  1583. (obj->base.size >> PAGE_SHIFT) - view.partial.offset);
  1584. /* If the partial covers the entire object, just create a normal VMA. */
  1585. if (chunk >= obj->base.size >> PAGE_SHIFT)
  1586. view.type = I915_GGTT_VIEW_NORMAL;
  1587. return view;
  1588. }
  1589. /**
  1590. * i915_gem_fault - fault a page into the GTT
  1591. * @vmf: fault info
  1592. *
  1593. * The fault handler is set up by drm_gem_mmap() when a object is GTT mapped
  1594. * from userspace. The fault handler takes care of binding the object to
  1595. * the GTT (if needed), allocating and programming a fence register (again,
  1596. * only if needed based on whether the old reg is still valid or the object
  1597. * is tiled) and inserting a new PTE into the faulting process.
  1598. *
  1599. * Note that the faulting process may involve evicting existing objects
  1600. * from the GTT and/or fence registers to make room. So performance may
  1601. * suffer if the GTT working set is large or there are few fence registers
  1602. * left.
  1603. *
  1604. * The current feature set supported by i915_gem_fault() and thus GTT mmaps
  1605. * is exposed via I915_PARAM_MMAP_GTT_VERSION (see i915_gem_mmap_gtt_version).
  1606. */
  1607. int i915_gem_fault(struct vm_fault *vmf)
  1608. {
  1609. #define MIN_CHUNK_PAGES ((1 << 20) >> PAGE_SHIFT) /* 1 MiB */
  1610. struct vm_area_struct *area = vmf->vma;
  1611. struct drm_i915_gem_object *obj = to_intel_bo(area->vm_private_data);
  1612. struct drm_device *dev = obj->base.dev;
  1613. struct drm_i915_private *dev_priv = to_i915(dev);
  1614. struct i915_ggtt *ggtt = &dev_priv->ggtt;
  1615. bool write = !!(vmf->flags & FAULT_FLAG_WRITE);
  1616. struct i915_vma *vma;
  1617. pgoff_t page_offset;
  1618. unsigned int flags;
  1619. int ret;
  1620. /* We don't use vmf->pgoff since that has the fake offset */
  1621. page_offset = (vmf->address - area->vm_start) >> PAGE_SHIFT;
  1622. trace_i915_gem_object_fault(obj, page_offset, true, write);
  1623. /* Try to flush the object off the GPU first without holding the lock.
  1624. * Upon acquiring the lock, we will perform our sanity checks and then
  1625. * repeat the flush holding the lock in the normal manner to catch cases
  1626. * where we are gazumped.
  1627. */
  1628. ret = i915_gem_object_wait(obj,
  1629. I915_WAIT_INTERRUPTIBLE,
  1630. MAX_SCHEDULE_TIMEOUT,
  1631. NULL);
  1632. if (ret)
  1633. goto err;
  1634. ret = i915_gem_object_pin_pages(obj);
  1635. if (ret)
  1636. goto err;
  1637. intel_runtime_pm_get(dev_priv);
  1638. ret = i915_mutex_lock_interruptible(dev);
  1639. if (ret)
  1640. goto err_rpm;
  1641. /* Access to snoopable pages through the GTT is incoherent. */
  1642. if (obj->cache_level != I915_CACHE_NONE && !HAS_LLC(dev_priv)) {
  1643. ret = -EFAULT;
  1644. goto err_unlock;
  1645. }
  1646. /* If the object is smaller than a couple of partial vma, it is
  1647. * not worth only creating a single partial vma - we may as well
  1648. * clear enough space for the full object.
  1649. */
  1650. flags = PIN_MAPPABLE;
  1651. if (obj->base.size > 2 * MIN_CHUNK_PAGES << PAGE_SHIFT)
  1652. flags |= PIN_NONBLOCK | PIN_NONFAULT;
  1653. /* Now pin it into the GTT as needed */
  1654. vma = i915_gem_object_ggtt_pin(obj, NULL, 0, 0, flags);
  1655. if (IS_ERR(vma)) {
  1656. /* Use a partial view if it is bigger than available space */
  1657. struct i915_ggtt_view view =
  1658. compute_partial_view(obj, page_offset, MIN_CHUNK_PAGES);
  1659. /* Userspace is now writing through an untracked VMA, abandon
  1660. * all hope that the hardware is able to track future writes.
  1661. */
  1662. obj->frontbuffer_ggtt_origin = ORIGIN_CPU;
  1663. vma = i915_gem_object_ggtt_pin(obj, &view, 0, 0, PIN_MAPPABLE);
  1664. }
  1665. if (IS_ERR(vma)) {
  1666. ret = PTR_ERR(vma);
  1667. goto err_unlock;
  1668. }
  1669. ret = i915_gem_object_set_to_gtt_domain(obj, write);
  1670. if (ret)
  1671. goto err_unpin;
  1672. ret = i915_vma_pin_fence(vma);
  1673. if (ret)
  1674. goto err_unpin;
  1675. /* Finally, remap it using the new GTT offset */
  1676. ret = remap_io_mapping(area,
  1677. area->vm_start + (vma->ggtt_view.partial.offset << PAGE_SHIFT),
  1678. (ggtt->gmadr.start + vma->node.start) >> PAGE_SHIFT,
  1679. min_t(u64, vma->size, area->vm_end - area->vm_start),
  1680. &ggtt->iomap);
  1681. if (ret)
  1682. goto err_fence;
  1683. /* Mark as being mmapped into userspace for later revocation */
  1684. assert_rpm_wakelock_held(dev_priv);
  1685. if (!i915_vma_set_userfault(vma) && !obj->userfault_count++)
  1686. list_add(&obj->userfault_link, &dev_priv->mm.userfault_list);
  1687. GEM_BUG_ON(!obj->userfault_count);
  1688. i915_vma_set_ggtt_write(vma);
  1689. err_fence:
  1690. i915_vma_unpin_fence(vma);
  1691. err_unpin:
  1692. __i915_vma_unpin(vma);
  1693. err_unlock:
  1694. mutex_unlock(&dev->struct_mutex);
  1695. err_rpm:
  1696. intel_runtime_pm_put(dev_priv);
  1697. i915_gem_object_unpin_pages(obj);
  1698. err:
  1699. switch (ret) {
  1700. case -EIO:
  1701. /*
  1702. * We eat errors when the gpu is terminally wedged to avoid
  1703. * userspace unduly crashing (gl has no provisions for mmaps to
  1704. * fail). But any other -EIO isn't ours (e.g. swap in failure)
  1705. * and so needs to be reported.
  1706. */
  1707. if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
  1708. ret = VM_FAULT_SIGBUS;
  1709. break;
  1710. }
  1711. case -EAGAIN:
  1712. /*
  1713. * EAGAIN means the gpu is hung and we'll wait for the error
  1714. * handler to reset everything when re-faulting in
  1715. * i915_mutex_lock_interruptible.
  1716. */
  1717. case 0:
  1718. case -ERESTARTSYS:
  1719. case -EINTR:
  1720. case -EBUSY:
  1721. /*
  1722. * EBUSY is ok: this just means that another thread
  1723. * already did the job.
  1724. */
  1725. ret = VM_FAULT_NOPAGE;
  1726. break;
  1727. case -ENOMEM:
  1728. ret = VM_FAULT_OOM;
  1729. break;
  1730. case -ENOSPC:
  1731. case -EFAULT:
  1732. ret = VM_FAULT_SIGBUS;
  1733. break;
  1734. default:
  1735. WARN_ONCE(ret, "unhandled error in i915_gem_fault: %i\n", ret);
  1736. ret = VM_FAULT_SIGBUS;
  1737. break;
  1738. }
  1739. return ret;
  1740. }
  1741. static void __i915_gem_object_release_mmap(struct drm_i915_gem_object *obj)
  1742. {
  1743. struct i915_vma *vma;
  1744. GEM_BUG_ON(!obj->userfault_count);
  1745. obj->userfault_count = 0;
  1746. list_del(&obj->userfault_link);
  1747. drm_vma_node_unmap(&obj->base.vma_node,
  1748. obj->base.dev->anon_inode->i_mapping);
  1749. for_each_ggtt_vma(vma, obj)
  1750. i915_vma_unset_userfault(vma);
  1751. }
  1752. /**
  1753. * i915_gem_release_mmap - remove physical page mappings
  1754. * @obj: obj in question
  1755. *
  1756. * Preserve the reservation of the mmapping with the DRM core code, but
  1757. * relinquish ownership of the pages back to the system.
  1758. *
  1759. * It is vital that we remove the page mapping if we have mapped a tiled
  1760. * object through the GTT and then lose the fence register due to
  1761. * resource pressure. Similarly if the object has been moved out of the
  1762. * aperture, than pages mapped into userspace must be revoked. Removing the
  1763. * mapping will then trigger a page fault on the next user access, allowing
  1764. * fixup by i915_gem_fault().
  1765. */
  1766. void
  1767. i915_gem_release_mmap(struct drm_i915_gem_object *obj)
  1768. {
  1769. struct drm_i915_private *i915 = to_i915(obj->base.dev);
  1770. /* Serialisation between user GTT access and our code depends upon
  1771. * revoking the CPU's PTE whilst the mutex is held. The next user
  1772. * pagefault then has to wait until we release the mutex.
  1773. *
  1774. * Note that RPM complicates somewhat by adding an additional
  1775. * requirement that operations to the GGTT be made holding the RPM
  1776. * wakeref.
  1777. */
  1778. lockdep_assert_held(&i915->drm.struct_mutex);
  1779. intel_runtime_pm_get(i915);
  1780. if (!obj->userfault_count)
  1781. goto out;
  1782. __i915_gem_object_release_mmap(obj);
  1783. /* Ensure that the CPU's PTE are revoked and there are not outstanding
  1784. * memory transactions from userspace before we return. The TLB
  1785. * flushing implied above by changing the PTE above *should* be
  1786. * sufficient, an extra barrier here just provides us with a bit
  1787. * of paranoid documentation about our requirement to serialise
  1788. * memory writes before touching registers / GSM.
  1789. */
  1790. wmb();
  1791. out:
  1792. intel_runtime_pm_put(i915);
  1793. }
  1794. void i915_gem_runtime_suspend(struct drm_i915_private *dev_priv)
  1795. {
  1796. struct drm_i915_gem_object *obj, *on;
  1797. int i;
  1798. /*
  1799. * Only called during RPM suspend. All users of the userfault_list
  1800. * must be holding an RPM wakeref to ensure that this can not
  1801. * run concurrently with themselves (and use the struct_mutex for
  1802. * protection between themselves).
  1803. */
  1804. list_for_each_entry_safe(obj, on,
  1805. &dev_priv->mm.userfault_list, userfault_link)
  1806. __i915_gem_object_release_mmap(obj);
  1807. /* The fence will be lost when the device powers down. If any were
  1808. * in use by hardware (i.e. they are pinned), we should not be powering
  1809. * down! All other fences will be reacquired by the user upon waking.
  1810. */
  1811. for (i = 0; i < dev_priv->num_fence_regs; i++) {
  1812. struct drm_i915_fence_reg *reg = &dev_priv->fence_regs[i];
  1813. /* Ideally we want to assert that the fence register is not
  1814. * live at this point (i.e. that no piece of code will be
  1815. * trying to write through fence + GTT, as that both violates
  1816. * our tracking of activity and associated locking/barriers,
  1817. * but also is illegal given that the hw is powered down).
  1818. *
  1819. * Previously we used reg->pin_count as a "liveness" indicator.
  1820. * That is not sufficient, and we need a more fine-grained
  1821. * tool if we want to have a sanity check here.
  1822. */
  1823. if (!reg->vma)
  1824. continue;
  1825. GEM_BUG_ON(i915_vma_has_userfault(reg->vma));
  1826. reg->dirty = true;
  1827. }
  1828. }
  1829. static int i915_gem_object_create_mmap_offset(struct drm_i915_gem_object *obj)
  1830. {
  1831. struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
  1832. int err;
  1833. err = drm_gem_create_mmap_offset(&obj->base);
  1834. if (likely(!err))
  1835. return 0;
  1836. /* Attempt to reap some mmap space from dead objects */
  1837. do {
  1838. err = i915_gem_wait_for_idle(dev_priv, I915_WAIT_INTERRUPTIBLE);
  1839. if (err)
  1840. break;
  1841. i915_gem_drain_freed_objects(dev_priv);
  1842. err = drm_gem_create_mmap_offset(&obj->base);
  1843. if (!err)
  1844. break;
  1845. } while (flush_delayed_work(&dev_priv->gt.retire_work));
  1846. return err;
  1847. }
  1848. static void i915_gem_object_free_mmap_offset(struct drm_i915_gem_object *obj)
  1849. {
  1850. drm_gem_free_mmap_offset(&obj->base);
  1851. }
  1852. int
  1853. i915_gem_mmap_gtt(struct drm_file *file,
  1854. struct drm_device *dev,
  1855. uint32_t handle,
  1856. uint64_t *offset)
  1857. {
  1858. struct drm_i915_gem_object *obj;
  1859. int ret;
  1860. obj = i915_gem_object_lookup(file, handle);
  1861. if (!obj)
  1862. return -ENOENT;
  1863. ret = i915_gem_object_create_mmap_offset(obj);
  1864. if (ret == 0)
  1865. *offset = drm_vma_node_offset_addr(&obj->base.vma_node);
  1866. i915_gem_object_put(obj);
  1867. return ret;
  1868. }
  1869. /**
  1870. * i915_gem_mmap_gtt_ioctl - prepare an object for GTT mmap'ing
  1871. * @dev: DRM device
  1872. * @data: GTT mapping ioctl data
  1873. * @file: GEM object info
  1874. *
  1875. * Simply returns the fake offset to userspace so it can mmap it.
  1876. * The mmap call will end up in drm_gem_mmap(), which will set things
  1877. * up so we can get faults in the handler above.
  1878. *
  1879. * The fault handler will take care of binding the object into the GTT
  1880. * (since it may have been evicted to make room for something), allocating
  1881. * a fence register, and mapping the appropriate aperture address into
  1882. * userspace.
  1883. */
  1884. int
  1885. i915_gem_mmap_gtt_ioctl(struct drm_device *dev, void *data,
  1886. struct drm_file *file)
  1887. {
  1888. struct drm_i915_gem_mmap_gtt *args = data;
  1889. return i915_gem_mmap_gtt(file, dev, args->handle, &args->offset);
  1890. }
  1891. /* Immediately discard the backing storage */
  1892. static void
  1893. i915_gem_object_truncate(struct drm_i915_gem_object *obj)
  1894. {
  1895. i915_gem_object_free_mmap_offset(obj);
  1896. if (obj->base.filp == NULL)
  1897. return;
  1898. /* Our goal here is to return as much of the memory as
  1899. * is possible back to the system as we are called from OOM.
  1900. * To do this we must instruct the shmfs to drop all of its
  1901. * backing pages, *now*.
  1902. */
  1903. shmem_truncate_range(file_inode(obj->base.filp), 0, (loff_t)-1);
  1904. obj->mm.madv = __I915_MADV_PURGED;
  1905. obj->mm.pages = ERR_PTR(-EFAULT);
  1906. }
  1907. /* Try to discard unwanted pages */
  1908. void __i915_gem_object_invalidate(struct drm_i915_gem_object *obj)
  1909. {
  1910. struct address_space *mapping;
  1911. lockdep_assert_held(&obj->mm.lock);
  1912. GEM_BUG_ON(i915_gem_object_has_pages(obj));
  1913. switch (obj->mm.madv) {
  1914. case I915_MADV_DONTNEED:
  1915. i915_gem_object_truncate(obj);
  1916. case __I915_MADV_PURGED:
  1917. return;
  1918. }
  1919. if (obj->base.filp == NULL)
  1920. return;
  1921. mapping = obj->base.filp->f_mapping,
  1922. invalidate_mapping_pages(mapping, 0, (loff_t)-1);
  1923. }
  1924. static void
  1925. i915_gem_object_put_pages_gtt(struct drm_i915_gem_object *obj,
  1926. struct sg_table *pages)
  1927. {
  1928. struct sgt_iter sgt_iter;
  1929. struct page *page;
  1930. __i915_gem_object_release_shmem(obj, pages, true);
  1931. i915_gem_gtt_finish_pages(obj, pages);
  1932. if (i915_gem_object_needs_bit17_swizzle(obj))
  1933. i915_gem_object_save_bit_17_swizzle(obj, pages);
  1934. for_each_sgt_page(page, sgt_iter, pages) {
  1935. if (obj->mm.dirty)
  1936. set_page_dirty(page);
  1937. if (obj->mm.madv == I915_MADV_WILLNEED)
  1938. mark_page_accessed(page);
  1939. put_page(page);
  1940. }
  1941. obj->mm.dirty = false;
  1942. sg_free_table(pages);
  1943. kfree(pages);
  1944. }
  1945. static void __i915_gem_object_reset_page_iter(struct drm_i915_gem_object *obj)
  1946. {
  1947. struct radix_tree_iter iter;
  1948. void __rcu **slot;
  1949. rcu_read_lock();
  1950. radix_tree_for_each_slot(slot, &obj->mm.get_page.radix, &iter, 0)
  1951. radix_tree_delete(&obj->mm.get_page.radix, iter.index);
  1952. rcu_read_unlock();
  1953. }
  1954. void __i915_gem_object_put_pages(struct drm_i915_gem_object *obj,
  1955. enum i915_mm_subclass subclass)
  1956. {
  1957. struct drm_i915_private *i915 = to_i915(obj->base.dev);
  1958. struct sg_table *pages;
  1959. if (i915_gem_object_has_pinned_pages(obj))
  1960. return;
  1961. GEM_BUG_ON(obj->bind_count);
  1962. if (!i915_gem_object_has_pages(obj))
  1963. return;
  1964. /* May be called by shrinker from within get_pages() (on another bo) */
  1965. mutex_lock_nested(&obj->mm.lock, subclass);
  1966. if (unlikely(atomic_read(&obj->mm.pages_pin_count)))
  1967. goto unlock;
  1968. /* ->put_pages might need to allocate memory for the bit17 swizzle
  1969. * array, hence protect them from being reaped by removing them from gtt
  1970. * lists early. */
  1971. pages = fetch_and_zero(&obj->mm.pages);
  1972. GEM_BUG_ON(!pages);
  1973. spin_lock(&i915->mm.obj_lock);
  1974. list_del(&obj->mm.link);
  1975. spin_unlock(&i915->mm.obj_lock);
  1976. if (obj->mm.mapping) {
  1977. void *ptr;
  1978. ptr = page_mask_bits(obj->mm.mapping);
  1979. if (is_vmalloc_addr(ptr))
  1980. vunmap(ptr);
  1981. else
  1982. kunmap(kmap_to_page(ptr));
  1983. obj->mm.mapping = NULL;
  1984. }
  1985. __i915_gem_object_reset_page_iter(obj);
  1986. if (!IS_ERR(pages))
  1987. obj->ops->put_pages(obj, pages);
  1988. obj->mm.page_sizes.phys = obj->mm.page_sizes.sg = 0;
  1989. unlock:
  1990. mutex_unlock(&obj->mm.lock);
  1991. }
  1992. static bool i915_sg_trim(struct sg_table *orig_st)
  1993. {
  1994. struct sg_table new_st;
  1995. struct scatterlist *sg, *new_sg;
  1996. unsigned int i;
  1997. if (orig_st->nents == orig_st->orig_nents)
  1998. return false;
  1999. if (sg_alloc_table(&new_st, orig_st->nents, GFP_KERNEL | __GFP_NOWARN))
  2000. return false;
  2001. new_sg = new_st.sgl;
  2002. for_each_sg(orig_st->sgl, sg, orig_st->nents, i) {
  2003. sg_set_page(new_sg, sg_page(sg), sg->length, 0);
  2004. /* called before being DMA mapped, no need to copy sg->dma_* */
  2005. new_sg = sg_next(new_sg);
  2006. }
  2007. GEM_BUG_ON(new_sg); /* Should walk exactly nents and hit the end */
  2008. sg_free_table(orig_st);
  2009. *orig_st = new_st;
  2010. return true;
  2011. }
  2012. static int i915_gem_object_get_pages_gtt(struct drm_i915_gem_object *obj)
  2013. {
  2014. struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
  2015. const unsigned long page_count = obj->base.size / PAGE_SIZE;
  2016. unsigned long i;
  2017. struct address_space *mapping;
  2018. struct sg_table *st;
  2019. struct scatterlist *sg;
  2020. struct sgt_iter sgt_iter;
  2021. struct page *page;
  2022. unsigned long last_pfn = 0; /* suppress gcc warning */
  2023. unsigned int max_segment = i915_sg_segment_size();
  2024. unsigned int sg_page_sizes;
  2025. gfp_t noreclaim;
  2026. int ret;
  2027. /* Assert that the object is not currently in any GPU domain. As it
  2028. * wasn't in the GTT, there shouldn't be any way it could have been in
  2029. * a GPU cache
  2030. */
  2031. GEM_BUG_ON(obj->read_domains & I915_GEM_GPU_DOMAINS);
  2032. GEM_BUG_ON(obj->write_domain & I915_GEM_GPU_DOMAINS);
  2033. st = kmalloc(sizeof(*st), GFP_KERNEL);
  2034. if (st == NULL)
  2035. return -ENOMEM;
  2036. rebuild_st:
  2037. if (sg_alloc_table(st, page_count, GFP_KERNEL)) {
  2038. kfree(st);
  2039. return -ENOMEM;
  2040. }
  2041. /* Get the list of pages out of our struct file. They'll be pinned
  2042. * at this point until we release them.
  2043. *
  2044. * Fail silently without starting the shrinker
  2045. */
  2046. mapping = obj->base.filp->f_mapping;
  2047. noreclaim = mapping_gfp_constraint(mapping, ~__GFP_RECLAIM);
  2048. noreclaim |= __GFP_NORETRY | __GFP_NOWARN;
  2049. sg = st->sgl;
  2050. st->nents = 0;
  2051. sg_page_sizes = 0;
  2052. for (i = 0; i < page_count; i++) {
  2053. const unsigned int shrink[] = {
  2054. I915_SHRINK_BOUND | I915_SHRINK_UNBOUND | I915_SHRINK_PURGEABLE,
  2055. 0,
  2056. }, *s = shrink;
  2057. gfp_t gfp = noreclaim;
  2058. do {
  2059. page = shmem_read_mapping_page_gfp(mapping, i, gfp);
  2060. if (likely(!IS_ERR(page)))
  2061. break;
  2062. if (!*s) {
  2063. ret = PTR_ERR(page);
  2064. goto err_sg;
  2065. }
  2066. i915_gem_shrink(dev_priv, 2 * page_count, NULL, *s++);
  2067. cond_resched();
  2068. /* We've tried hard to allocate the memory by reaping
  2069. * our own buffer, now let the real VM do its job and
  2070. * go down in flames if truly OOM.
  2071. *
  2072. * However, since graphics tend to be disposable,
  2073. * defer the oom here by reporting the ENOMEM back
  2074. * to userspace.
  2075. */
  2076. if (!*s) {
  2077. /* reclaim and warn, but no oom */
  2078. gfp = mapping_gfp_mask(mapping);
  2079. /* Our bo are always dirty and so we require
  2080. * kswapd to reclaim our pages (direct reclaim
  2081. * does not effectively begin pageout of our
  2082. * buffers on its own). However, direct reclaim
  2083. * only waits for kswapd when under allocation
  2084. * congestion. So as a result __GFP_RECLAIM is
  2085. * unreliable and fails to actually reclaim our
  2086. * dirty pages -- unless you try over and over
  2087. * again with !__GFP_NORETRY. However, we still
  2088. * want to fail this allocation rather than
  2089. * trigger the out-of-memory killer and for
  2090. * this we want __GFP_RETRY_MAYFAIL.
  2091. */
  2092. gfp |= __GFP_RETRY_MAYFAIL;
  2093. }
  2094. } while (1);
  2095. if (!i ||
  2096. sg->length >= max_segment ||
  2097. page_to_pfn(page) != last_pfn + 1) {
  2098. if (i) {
  2099. sg_page_sizes |= sg->length;
  2100. sg = sg_next(sg);
  2101. }
  2102. st->nents++;
  2103. sg_set_page(sg, page, PAGE_SIZE, 0);
  2104. } else {
  2105. sg->length += PAGE_SIZE;
  2106. }
  2107. last_pfn = page_to_pfn(page);
  2108. /* Check that the i965g/gm workaround works. */
  2109. WARN_ON((gfp & __GFP_DMA32) && (last_pfn >= 0x00100000UL));
  2110. }
  2111. if (sg) { /* loop terminated early; short sg table */
  2112. sg_page_sizes |= sg->length;
  2113. sg_mark_end(sg);
  2114. }
  2115. /* Trim unused sg entries to avoid wasting memory. */
  2116. i915_sg_trim(st);
  2117. ret = i915_gem_gtt_prepare_pages(obj, st);
  2118. if (ret) {
  2119. /* DMA remapping failed? One possible cause is that
  2120. * it could not reserve enough large entries, asking
  2121. * for PAGE_SIZE chunks instead may be helpful.
  2122. */
  2123. if (max_segment > PAGE_SIZE) {
  2124. for_each_sgt_page(page, sgt_iter, st)
  2125. put_page(page);
  2126. sg_free_table(st);
  2127. max_segment = PAGE_SIZE;
  2128. goto rebuild_st;
  2129. } else {
  2130. dev_warn(&dev_priv->drm.pdev->dev,
  2131. "Failed to DMA remap %lu pages\n",
  2132. page_count);
  2133. goto err_pages;
  2134. }
  2135. }
  2136. if (i915_gem_object_needs_bit17_swizzle(obj))
  2137. i915_gem_object_do_bit_17_swizzle(obj, st);
  2138. __i915_gem_object_set_pages(obj, st, sg_page_sizes);
  2139. return 0;
  2140. err_sg:
  2141. sg_mark_end(sg);
  2142. err_pages:
  2143. for_each_sgt_page(page, sgt_iter, st)
  2144. put_page(page);
  2145. sg_free_table(st);
  2146. kfree(st);
  2147. /* shmemfs first checks if there is enough memory to allocate the page
  2148. * and reports ENOSPC should there be insufficient, along with the usual
  2149. * ENOMEM for a genuine allocation failure.
  2150. *
  2151. * We use ENOSPC in our driver to mean that we have run out of aperture
  2152. * space and so want to translate the error from shmemfs back to our
  2153. * usual understanding of ENOMEM.
  2154. */
  2155. if (ret == -ENOSPC)
  2156. ret = -ENOMEM;
  2157. return ret;
  2158. }
  2159. void __i915_gem_object_set_pages(struct drm_i915_gem_object *obj,
  2160. struct sg_table *pages,
  2161. unsigned int sg_page_sizes)
  2162. {
  2163. struct drm_i915_private *i915 = to_i915(obj->base.dev);
  2164. unsigned long supported = INTEL_INFO(i915)->page_sizes;
  2165. int i;
  2166. lockdep_assert_held(&obj->mm.lock);
  2167. obj->mm.get_page.sg_pos = pages->sgl;
  2168. obj->mm.get_page.sg_idx = 0;
  2169. obj->mm.pages = pages;
  2170. if (i915_gem_object_is_tiled(obj) &&
  2171. i915->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
  2172. GEM_BUG_ON(obj->mm.quirked);
  2173. __i915_gem_object_pin_pages(obj);
  2174. obj->mm.quirked = true;
  2175. }
  2176. GEM_BUG_ON(!sg_page_sizes);
  2177. obj->mm.page_sizes.phys = sg_page_sizes;
  2178. /*
  2179. * Calculate the supported page-sizes which fit into the given
  2180. * sg_page_sizes. This will give us the page-sizes which we may be able
  2181. * to use opportunistically when later inserting into the GTT. For
  2182. * example if phys=2G, then in theory we should be able to use 1G, 2M,
  2183. * 64K or 4K pages, although in practice this will depend on a number of
  2184. * other factors.
  2185. */
  2186. obj->mm.page_sizes.sg = 0;
  2187. for_each_set_bit(i, &supported, ilog2(I915_GTT_MAX_PAGE_SIZE) + 1) {
  2188. if (obj->mm.page_sizes.phys & ~0u << i)
  2189. obj->mm.page_sizes.sg |= BIT(i);
  2190. }
  2191. GEM_BUG_ON(!HAS_PAGE_SIZES(i915, obj->mm.page_sizes.sg));
  2192. spin_lock(&i915->mm.obj_lock);
  2193. list_add(&obj->mm.link, &i915->mm.unbound_list);
  2194. spin_unlock(&i915->mm.obj_lock);
  2195. }
  2196. static int ____i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
  2197. {
  2198. int err;
  2199. if (unlikely(obj->mm.madv != I915_MADV_WILLNEED)) {
  2200. DRM_DEBUG("Attempting to obtain a purgeable object\n");
  2201. return -EFAULT;
  2202. }
  2203. err = obj->ops->get_pages(obj);
  2204. GEM_BUG_ON(!err && !i915_gem_object_has_pages(obj));
  2205. return err;
  2206. }
  2207. /* Ensure that the associated pages are gathered from the backing storage
  2208. * and pinned into our object. i915_gem_object_pin_pages() may be called
  2209. * multiple times before they are released by a single call to
  2210. * i915_gem_object_unpin_pages() - once the pages are no longer referenced
  2211. * either as a result of memory pressure (reaping pages under the shrinker)
  2212. * or as the object is itself released.
  2213. */
  2214. int __i915_gem_object_get_pages(struct drm_i915_gem_object *obj)
  2215. {
  2216. int err;
  2217. err = mutex_lock_interruptible(&obj->mm.lock);
  2218. if (err)
  2219. return err;
  2220. if (unlikely(!i915_gem_object_has_pages(obj))) {
  2221. GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
  2222. err = ____i915_gem_object_get_pages(obj);
  2223. if (err)
  2224. goto unlock;
  2225. smp_mb__before_atomic();
  2226. }
  2227. atomic_inc(&obj->mm.pages_pin_count);
  2228. unlock:
  2229. mutex_unlock(&obj->mm.lock);
  2230. return err;
  2231. }
  2232. /* The 'mapping' part of i915_gem_object_pin_map() below */
  2233. static void *i915_gem_object_map(const struct drm_i915_gem_object *obj,
  2234. enum i915_map_type type)
  2235. {
  2236. unsigned long n_pages = obj->base.size >> PAGE_SHIFT;
  2237. struct sg_table *sgt = obj->mm.pages;
  2238. struct sgt_iter sgt_iter;
  2239. struct page *page;
  2240. struct page *stack_pages[32];
  2241. struct page **pages = stack_pages;
  2242. unsigned long i = 0;
  2243. pgprot_t pgprot;
  2244. void *addr;
  2245. /* A single page can always be kmapped */
  2246. if (n_pages == 1 && type == I915_MAP_WB)
  2247. return kmap(sg_page(sgt->sgl));
  2248. if (n_pages > ARRAY_SIZE(stack_pages)) {
  2249. /* Too big for stack -- allocate temporary array instead */
  2250. pages = kvmalloc_array(n_pages, sizeof(*pages), GFP_KERNEL);
  2251. if (!pages)
  2252. return NULL;
  2253. }
  2254. for_each_sgt_page(page, sgt_iter, sgt)
  2255. pages[i++] = page;
  2256. /* Check that we have the expected number of pages */
  2257. GEM_BUG_ON(i != n_pages);
  2258. switch (type) {
  2259. default:
  2260. MISSING_CASE(type);
  2261. /* fallthrough to use PAGE_KERNEL anyway */
  2262. case I915_MAP_WB:
  2263. pgprot = PAGE_KERNEL;
  2264. break;
  2265. case I915_MAP_WC:
  2266. pgprot = pgprot_writecombine(PAGE_KERNEL_IO);
  2267. break;
  2268. }
  2269. addr = vmap(pages, n_pages, 0, pgprot);
  2270. if (pages != stack_pages)
  2271. kvfree(pages);
  2272. return addr;
  2273. }
  2274. /* get, pin, and map the pages of the object into kernel space */
  2275. void *i915_gem_object_pin_map(struct drm_i915_gem_object *obj,
  2276. enum i915_map_type type)
  2277. {
  2278. enum i915_map_type has_type;
  2279. bool pinned;
  2280. void *ptr;
  2281. int ret;
  2282. if (unlikely(!i915_gem_object_has_struct_page(obj)))
  2283. return ERR_PTR(-ENXIO);
  2284. ret = mutex_lock_interruptible(&obj->mm.lock);
  2285. if (ret)
  2286. return ERR_PTR(ret);
  2287. pinned = !(type & I915_MAP_OVERRIDE);
  2288. type &= ~I915_MAP_OVERRIDE;
  2289. if (!atomic_inc_not_zero(&obj->mm.pages_pin_count)) {
  2290. if (unlikely(!i915_gem_object_has_pages(obj))) {
  2291. GEM_BUG_ON(i915_gem_object_has_pinned_pages(obj));
  2292. ret = ____i915_gem_object_get_pages(obj);
  2293. if (ret)
  2294. goto err_unlock;
  2295. smp_mb__before_atomic();
  2296. }
  2297. atomic_inc(&obj->mm.pages_pin_count);
  2298. pinned = false;
  2299. }
  2300. GEM_BUG_ON(!i915_gem_object_has_pages(obj));
  2301. ptr = page_unpack_bits(obj->mm.mapping, &has_type);
  2302. if (ptr && has_type != type) {
  2303. if (pinned) {
  2304. ret = -EBUSY;
  2305. goto err_unpin;
  2306. }
  2307. if (is_vmalloc_addr(ptr))
  2308. vunmap(ptr);
  2309. else
  2310. kunmap(kmap_to_page(ptr));
  2311. ptr = obj->mm.mapping = NULL;
  2312. }
  2313. if (!ptr) {
  2314. ptr = i915_gem_object_map(obj, type);
  2315. if (!ptr) {
  2316. ret = -ENOMEM;
  2317. goto err_unpin;
  2318. }
  2319. obj->mm.mapping = page_pack_bits(ptr, type);
  2320. }
  2321. out_unlock:
  2322. mutex_unlock(&obj->mm.lock);
  2323. return ptr;
  2324. err_unpin:
  2325. atomic_dec(&obj->mm.pages_pin_count);
  2326. err_unlock:
  2327. ptr = ERR_PTR(ret);
  2328. goto out_unlock;
  2329. }
  2330. static int
  2331. i915_gem_object_pwrite_gtt(struct drm_i915_gem_object *obj,
  2332. const struct drm_i915_gem_pwrite *arg)
  2333. {
  2334. struct address_space *mapping = obj->base.filp->f_mapping;
  2335. char __user *user_data = u64_to_user_ptr(arg->data_ptr);
  2336. u64 remain, offset;
  2337. unsigned int pg;
  2338. /* Before we instantiate/pin the backing store for our use, we
  2339. * can prepopulate the shmemfs filp efficiently using a write into
  2340. * the pagecache. We avoid the penalty of instantiating all the
  2341. * pages, important if the user is just writing to a few and never
  2342. * uses the object on the GPU, and using a direct write into shmemfs
  2343. * allows it to avoid the cost of retrieving a page (either swapin
  2344. * or clearing-before-use) before it is overwritten.
  2345. */
  2346. if (i915_gem_object_has_pages(obj))
  2347. return -ENODEV;
  2348. if (obj->mm.madv != I915_MADV_WILLNEED)
  2349. return -EFAULT;
  2350. /* Before the pages are instantiated the object is treated as being
  2351. * in the CPU domain. The pages will be clflushed as required before
  2352. * use, and we can freely write into the pages directly. If userspace
  2353. * races pwrite with any other operation; corruption will ensue -
  2354. * that is userspace's prerogative!
  2355. */
  2356. remain = arg->size;
  2357. offset = arg->offset;
  2358. pg = offset_in_page(offset);
  2359. do {
  2360. unsigned int len, unwritten;
  2361. struct page *page;
  2362. void *data, *vaddr;
  2363. int err;
  2364. len = PAGE_SIZE - pg;
  2365. if (len > remain)
  2366. len = remain;
  2367. err = pagecache_write_begin(obj->base.filp, mapping,
  2368. offset, len, 0,
  2369. &page, &data);
  2370. if (err < 0)
  2371. return err;
  2372. vaddr = kmap(page);
  2373. unwritten = copy_from_user(vaddr + pg, user_data, len);
  2374. kunmap(page);
  2375. err = pagecache_write_end(obj->base.filp, mapping,
  2376. offset, len, len - unwritten,
  2377. page, data);
  2378. if (err < 0)
  2379. return err;
  2380. if (unwritten)
  2381. return -EFAULT;
  2382. remain -= len;
  2383. user_data += len;
  2384. offset += len;
  2385. pg = 0;
  2386. } while (remain);
  2387. return 0;
  2388. }
  2389. static void i915_gem_context_mark_guilty(struct i915_gem_context *ctx)
  2390. {
  2391. bool banned;
  2392. atomic_inc(&ctx->guilty_count);
  2393. banned = false;
  2394. if (i915_gem_context_is_bannable(ctx)) {
  2395. unsigned int score;
  2396. score = atomic_add_return(CONTEXT_SCORE_GUILTY,
  2397. &ctx->ban_score);
  2398. banned = score >= CONTEXT_SCORE_BAN_THRESHOLD;
  2399. DRM_DEBUG_DRIVER("context %s marked guilty (score %d) banned? %s\n",
  2400. ctx->name, score, yesno(banned));
  2401. }
  2402. if (!banned)
  2403. return;
  2404. i915_gem_context_set_banned(ctx);
  2405. if (!IS_ERR_OR_NULL(ctx->file_priv)) {
  2406. atomic_inc(&ctx->file_priv->context_bans);
  2407. DRM_DEBUG_DRIVER("client %s has had %d context banned\n",
  2408. ctx->name, atomic_read(&ctx->file_priv->context_bans));
  2409. }
  2410. }
  2411. static void i915_gem_context_mark_innocent(struct i915_gem_context *ctx)
  2412. {
  2413. atomic_inc(&ctx->active_count);
  2414. }
  2415. struct i915_request *
  2416. i915_gem_find_active_request(struct intel_engine_cs *engine)
  2417. {
  2418. struct i915_request *request, *active = NULL;
  2419. unsigned long flags;
  2420. /* We are called by the error capture and reset at a random
  2421. * point in time. In particular, note that neither is crucially
  2422. * ordered with an interrupt. After a hang, the GPU is dead and we
  2423. * assume that no more writes can happen (we waited long enough for
  2424. * all writes that were in transaction to be flushed) - adding an
  2425. * extra delay for a recent interrupt is pointless. Hence, we do
  2426. * not need an engine->irq_seqno_barrier() before the seqno reads.
  2427. */
  2428. spin_lock_irqsave(&engine->timeline->lock, flags);
  2429. list_for_each_entry(request, &engine->timeline->requests, link) {
  2430. if (__i915_request_completed(request, request->global_seqno))
  2431. continue;
  2432. GEM_BUG_ON(request->engine != engine);
  2433. GEM_BUG_ON(test_bit(DMA_FENCE_FLAG_SIGNALED_BIT,
  2434. &request->fence.flags));
  2435. active = request;
  2436. break;
  2437. }
  2438. spin_unlock_irqrestore(&engine->timeline->lock, flags);
  2439. return active;
  2440. }
  2441. static bool engine_stalled(struct intel_engine_cs *engine)
  2442. {
  2443. if (!engine->hangcheck.stalled)
  2444. return false;
  2445. /* Check for possible seqno movement after hang declaration */
  2446. if (engine->hangcheck.seqno != intel_engine_get_seqno(engine)) {
  2447. DRM_DEBUG_DRIVER("%s pardoned\n", engine->name);
  2448. return false;
  2449. }
  2450. return true;
  2451. }
  2452. /*
  2453. * Ensure irq handler finishes, and not run again.
  2454. * Also return the active request so that we only search for it once.
  2455. */
  2456. struct i915_request *
  2457. i915_gem_reset_prepare_engine(struct intel_engine_cs *engine)
  2458. {
  2459. struct i915_request *request = NULL;
  2460. /*
  2461. * During the reset sequence, we must prevent the engine from
  2462. * entering RC6. As the context state is undefined until we restart
  2463. * the engine, if it does enter RC6 during the reset, the state
  2464. * written to the powercontext is undefined and so we may lose
  2465. * GPU state upon resume, i.e. fail to restart after a reset.
  2466. */
  2467. intel_uncore_forcewake_get(engine->i915, FORCEWAKE_ALL);
  2468. /*
  2469. * Prevent the signaler thread from updating the request
  2470. * state (by calling dma_fence_signal) as we are processing
  2471. * the reset. The write from the GPU of the seqno is
  2472. * asynchronous and the signaler thread may see a different
  2473. * value to us and declare the request complete, even though
  2474. * the reset routine have picked that request as the active
  2475. * (incomplete) request. This conflict is not handled
  2476. * gracefully!
  2477. */
  2478. kthread_park(engine->breadcrumbs.signaler);
  2479. /*
  2480. * Prevent request submission to the hardware until we have
  2481. * completed the reset in i915_gem_reset_finish(). If a request
  2482. * is completed by one engine, it may then queue a request
  2483. * to a second via its execlists->tasklet *just* as we are
  2484. * calling engine->init_hw() and also writing the ELSP.
  2485. * Turning off the execlists->tasklet until the reset is over
  2486. * prevents the race.
  2487. *
  2488. * Note that this needs to be a single atomic operation on the
  2489. * tasklet (flush existing tasks, prevent new tasks) to prevent
  2490. * a race between reset and set-wedged. It is not, so we do the best
  2491. * we can atm and make sure we don't lock the machine up in the more
  2492. * common case of recursively being called from set-wedged from inside
  2493. * i915_reset.
  2494. */
  2495. if (!atomic_read(&engine->execlists.tasklet.count))
  2496. tasklet_kill(&engine->execlists.tasklet);
  2497. tasklet_disable(&engine->execlists.tasklet);
  2498. /*
  2499. * We're using worker to queue preemption requests from the tasklet in
  2500. * GuC submission mode.
  2501. * Even though tasklet was disabled, we may still have a worker queued.
  2502. * Let's make sure that all workers scheduled before disabling the
  2503. * tasklet are completed before continuing with the reset.
  2504. */
  2505. if (engine->i915->guc.preempt_wq)
  2506. flush_workqueue(engine->i915->guc.preempt_wq);
  2507. if (engine->irq_seqno_barrier)
  2508. engine->irq_seqno_barrier(engine);
  2509. request = i915_gem_find_active_request(engine);
  2510. if (request && request->fence.error == -EIO)
  2511. request = ERR_PTR(-EIO); /* Previous reset failed! */
  2512. return request;
  2513. }
  2514. int i915_gem_reset_prepare(struct drm_i915_private *dev_priv)
  2515. {
  2516. struct intel_engine_cs *engine;
  2517. struct i915_request *request;
  2518. enum intel_engine_id id;
  2519. int err = 0;
  2520. for_each_engine(engine, dev_priv, id) {
  2521. request = i915_gem_reset_prepare_engine(engine);
  2522. if (IS_ERR(request)) {
  2523. err = PTR_ERR(request);
  2524. continue;
  2525. }
  2526. engine->hangcheck.active_request = request;
  2527. }
  2528. i915_gem_revoke_fences(dev_priv);
  2529. return err;
  2530. }
  2531. static void skip_request(struct i915_request *request)
  2532. {
  2533. void *vaddr = request->ring->vaddr;
  2534. u32 head;
  2535. /* As this request likely depends on state from the lost
  2536. * context, clear out all the user operations leaving the
  2537. * breadcrumb at the end (so we get the fence notifications).
  2538. */
  2539. head = request->head;
  2540. if (request->postfix < head) {
  2541. memset(vaddr + head, 0, request->ring->size - head);
  2542. head = 0;
  2543. }
  2544. memset(vaddr + head, 0, request->postfix - head);
  2545. dma_fence_set_error(&request->fence, -EIO);
  2546. }
  2547. static void engine_skip_context(struct i915_request *request)
  2548. {
  2549. struct intel_engine_cs *engine = request->engine;
  2550. struct i915_gem_context *hung_ctx = request->ctx;
  2551. struct intel_timeline *timeline;
  2552. unsigned long flags;
  2553. timeline = i915_gem_context_lookup_timeline(hung_ctx, engine);
  2554. spin_lock_irqsave(&engine->timeline->lock, flags);
  2555. spin_lock(&timeline->lock);
  2556. list_for_each_entry_continue(request, &engine->timeline->requests, link)
  2557. if (request->ctx == hung_ctx)
  2558. skip_request(request);
  2559. list_for_each_entry(request, &timeline->requests, link)
  2560. skip_request(request);
  2561. spin_unlock(&timeline->lock);
  2562. spin_unlock_irqrestore(&engine->timeline->lock, flags);
  2563. }
  2564. /* Returns the request if it was guilty of the hang */
  2565. static struct i915_request *
  2566. i915_gem_reset_request(struct intel_engine_cs *engine,
  2567. struct i915_request *request)
  2568. {
  2569. /* The guilty request will get skipped on a hung engine.
  2570. *
  2571. * Users of client default contexts do not rely on logical
  2572. * state preserved between batches so it is safe to execute
  2573. * queued requests following the hang. Non default contexts
  2574. * rely on preserved state, so skipping a batch loses the
  2575. * evolution of the state and it needs to be considered corrupted.
  2576. * Executing more queued batches on top of corrupted state is
  2577. * risky. But we take the risk by trying to advance through
  2578. * the queued requests in order to make the client behaviour
  2579. * more predictable around resets, by not throwing away random
  2580. * amount of batches it has prepared for execution. Sophisticated
  2581. * clients can use gem_reset_stats_ioctl and dma fence status
  2582. * (exported via sync_file info ioctl on explicit fences) to observe
  2583. * when it loses the context state and should rebuild accordingly.
  2584. *
  2585. * The context ban, and ultimately the client ban, mechanism are safety
  2586. * valves if client submission ends up resulting in nothing more than
  2587. * subsequent hangs.
  2588. */
  2589. if (engine_stalled(engine)) {
  2590. i915_gem_context_mark_guilty(request->ctx);
  2591. skip_request(request);
  2592. /* If this context is now banned, skip all pending requests. */
  2593. if (i915_gem_context_is_banned(request->ctx))
  2594. engine_skip_context(request);
  2595. } else {
  2596. /*
  2597. * Since this is not the hung engine, it may have advanced
  2598. * since the hang declaration. Double check by refinding
  2599. * the active request at the time of the reset.
  2600. */
  2601. request = i915_gem_find_active_request(engine);
  2602. if (request) {
  2603. i915_gem_context_mark_innocent(request->ctx);
  2604. dma_fence_set_error(&request->fence, -EAGAIN);
  2605. /* Rewind the engine to replay the incomplete rq */
  2606. spin_lock_irq(&engine->timeline->lock);
  2607. request = list_prev_entry(request, link);
  2608. if (&request->link == &engine->timeline->requests)
  2609. request = NULL;
  2610. spin_unlock_irq(&engine->timeline->lock);
  2611. }
  2612. }
  2613. return request;
  2614. }
  2615. void i915_gem_reset_engine(struct intel_engine_cs *engine,
  2616. struct i915_request *request)
  2617. {
  2618. /*
  2619. * Make sure this write is visible before we re-enable the interrupt
  2620. * handlers on another CPU, as tasklet_enable() resolves to just
  2621. * a compiler barrier which is insufficient for our purpose here.
  2622. */
  2623. smp_store_mb(engine->irq_posted, 0);
  2624. if (request)
  2625. request = i915_gem_reset_request(engine, request);
  2626. if (request) {
  2627. DRM_DEBUG_DRIVER("resetting %s to restart from tail of request 0x%x\n",
  2628. engine->name, request->global_seqno);
  2629. }
  2630. /* Setup the CS to resume from the breadcrumb of the hung request */
  2631. engine->reset_hw(engine, request);
  2632. }
  2633. void i915_gem_reset(struct drm_i915_private *dev_priv)
  2634. {
  2635. struct intel_engine_cs *engine;
  2636. enum intel_engine_id id;
  2637. lockdep_assert_held(&dev_priv->drm.struct_mutex);
  2638. i915_retire_requests(dev_priv);
  2639. for_each_engine(engine, dev_priv, id) {
  2640. struct i915_gem_context *ctx;
  2641. i915_gem_reset_engine(engine, engine->hangcheck.active_request);
  2642. ctx = fetch_and_zero(&engine->last_retired_context);
  2643. if (ctx)
  2644. engine->context_unpin(engine, ctx);
  2645. /*
  2646. * Ostensibily, we always want a context loaded for powersaving,
  2647. * so if the engine is idle after the reset, send a request
  2648. * to load our scratch kernel_context.
  2649. *
  2650. * More mysteriously, if we leave the engine idle after a reset,
  2651. * the next userspace batch may hang, with what appears to be
  2652. * an incoherent read by the CS (presumably stale TLB). An
  2653. * empty request appears sufficient to paper over the glitch.
  2654. */
  2655. if (intel_engine_is_idle(engine)) {
  2656. struct i915_request *rq;
  2657. rq = i915_request_alloc(engine,
  2658. dev_priv->kernel_context);
  2659. if (!IS_ERR(rq))
  2660. __i915_request_add(rq, false);
  2661. }
  2662. }
  2663. i915_gem_restore_fences(dev_priv);
  2664. if (dev_priv->gt.awake) {
  2665. intel_sanitize_gt_powersave(dev_priv);
  2666. intel_enable_gt_powersave(dev_priv);
  2667. if (INTEL_GEN(dev_priv) >= 6)
  2668. gen6_rps_busy(dev_priv);
  2669. }
  2670. }
  2671. void i915_gem_reset_finish_engine(struct intel_engine_cs *engine)
  2672. {
  2673. tasklet_enable(&engine->execlists.tasklet);
  2674. kthread_unpark(engine->breadcrumbs.signaler);
  2675. intel_uncore_forcewake_put(engine->i915, FORCEWAKE_ALL);
  2676. }
  2677. void i915_gem_reset_finish(struct drm_i915_private *dev_priv)
  2678. {
  2679. struct intel_engine_cs *engine;
  2680. enum intel_engine_id id;
  2681. lockdep_assert_held(&dev_priv->drm.struct_mutex);
  2682. for_each_engine(engine, dev_priv, id) {
  2683. engine->hangcheck.active_request = NULL;
  2684. i915_gem_reset_finish_engine(engine);
  2685. }
  2686. }
  2687. static void nop_submit_request(struct i915_request *request)
  2688. {
  2689. dma_fence_set_error(&request->fence, -EIO);
  2690. i915_request_submit(request);
  2691. }
  2692. static void nop_complete_submit_request(struct i915_request *request)
  2693. {
  2694. unsigned long flags;
  2695. dma_fence_set_error(&request->fence, -EIO);
  2696. spin_lock_irqsave(&request->engine->timeline->lock, flags);
  2697. __i915_request_submit(request);
  2698. intel_engine_init_global_seqno(request->engine, request->global_seqno);
  2699. spin_unlock_irqrestore(&request->engine->timeline->lock, flags);
  2700. }
  2701. void i915_gem_set_wedged(struct drm_i915_private *i915)
  2702. {
  2703. struct intel_engine_cs *engine;
  2704. enum intel_engine_id id;
  2705. if (drm_debug & DRM_UT_DRIVER) {
  2706. struct drm_printer p = drm_debug_printer(__func__);
  2707. for_each_engine(engine, i915, id)
  2708. intel_engine_dump(engine, &p, "%s\n", engine->name);
  2709. }
  2710. set_bit(I915_WEDGED, &i915->gpu_error.flags);
  2711. smp_mb__after_atomic();
  2712. /*
  2713. * First, stop submission to hw, but do not yet complete requests by
  2714. * rolling the global seqno forward (since this would complete requests
  2715. * for which we haven't set the fence error to EIO yet).
  2716. */
  2717. for_each_engine(engine, i915, id) {
  2718. i915_gem_reset_prepare_engine(engine);
  2719. engine->submit_request = nop_submit_request;
  2720. engine->schedule = NULL;
  2721. }
  2722. i915->caps.scheduler = 0;
  2723. /*
  2724. * Make sure no one is running the old callback before we proceed with
  2725. * cancelling requests and resetting the completion tracking. Otherwise
  2726. * we might submit a request to the hardware which never completes.
  2727. */
  2728. synchronize_rcu();
  2729. for_each_engine(engine, i915, id) {
  2730. /* Mark all executing requests as skipped */
  2731. engine->cancel_requests(engine);
  2732. /*
  2733. * Only once we've force-cancelled all in-flight requests can we
  2734. * start to complete all requests.
  2735. */
  2736. engine->submit_request = nop_complete_submit_request;
  2737. }
  2738. /*
  2739. * Make sure no request can slip through without getting completed by
  2740. * either this call here to intel_engine_init_global_seqno, or the one
  2741. * in nop_complete_submit_request.
  2742. */
  2743. synchronize_rcu();
  2744. for_each_engine(engine, i915, id) {
  2745. unsigned long flags;
  2746. /*
  2747. * Mark all pending requests as complete so that any concurrent
  2748. * (lockless) lookup doesn't try and wait upon the request as we
  2749. * reset it.
  2750. */
  2751. spin_lock_irqsave(&engine->timeline->lock, flags);
  2752. intel_engine_init_global_seqno(engine,
  2753. intel_engine_last_submit(engine));
  2754. spin_unlock_irqrestore(&engine->timeline->lock, flags);
  2755. i915_gem_reset_finish_engine(engine);
  2756. }
  2757. wake_up_all(&i915->gpu_error.reset_queue);
  2758. }
  2759. bool i915_gem_unset_wedged(struct drm_i915_private *i915)
  2760. {
  2761. struct i915_gem_timeline *tl;
  2762. int i;
  2763. lockdep_assert_held(&i915->drm.struct_mutex);
  2764. if (!test_bit(I915_WEDGED, &i915->gpu_error.flags))
  2765. return true;
  2766. /* Before unwedging, make sure that all pending operations
  2767. * are flushed and errored out - we may have requests waiting upon
  2768. * third party fences. We marked all inflight requests as EIO, and
  2769. * every execbuf since returned EIO, for consistency we want all
  2770. * the currently pending requests to also be marked as EIO, which
  2771. * is done inside our nop_submit_request - and so we must wait.
  2772. *
  2773. * No more can be submitted until we reset the wedged bit.
  2774. */
  2775. list_for_each_entry(tl, &i915->gt.timelines, link) {
  2776. for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
  2777. struct i915_request *rq;
  2778. rq = i915_gem_active_peek(&tl->engine[i].last_request,
  2779. &i915->drm.struct_mutex);
  2780. if (!rq)
  2781. continue;
  2782. /* We can't use our normal waiter as we want to
  2783. * avoid recursively trying to handle the current
  2784. * reset. The basic dma_fence_default_wait() installs
  2785. * a callback for dma_fence_signal(), which is
  2786. * triggered by our nop handler (indirectly, the
  2787. * callback enables the signaler thread which is
  2788. * woken by the nop_submit_request() advancing the seqno
  2789. * and when the seqno passes the fence, the signaler
  2790. * then signals the fence waking us up).
  2791. */
  2792. if (dma_fence_default_wait(&rq->fence, true,
  2793. MAX_SCHEDULE_TIMEOUT) < 0)
  2794. return false;
  2795. }
  2796. }
  2797. /* Undo nop_submit_request. We prevent all new i915 requests from
  2798. * being queued (by disallowing execbuf whilst wedged) so having
  2799. * waited for all active requests above, we know the system is idle
  2800. * and do not have to worry about a thread being inside
  2801. * engine->submit_request() as we swap over. So unlike installing
  2802. * the nop_submit_request on reset, we can do this from normal
  2803. * context and do not require stop_machine().
  2804. */
  2805. intel_engines_reset_default_submission(i915);
  2806. i915_gem_contexts_lost(i915);
  2807. smp_mb__before_atomic(); /* complete takeover before enabling execbuf */
  2808. clear_bit(I915_WEDGED, &i915->gpu_error.flags);
  2809. return true;
  2810. }
  2811. static void
  2812. i915_gem_retire_work_handler(struct work_struct *work)
  2813. {
  2814. struct drm_i915_private *dev_priv =
  2815. container_of(work, typeof(*dev_priv), gt.retire_work.work);
  2816. struct drm_device *dev = &dev_priv->drm;
  2817. /* Come back later if the device is busy... */
  2818. if (mutex_trylock(&dev->struct_mutex)) {
  2819. i915_retire_requests(dev_priv);
  2820. mutex_unlock(&dev->struct_mutex);
  2821. }
  2822. /*
  2823. * Keep the retire handler running until we are finally idle.
  2824. * We do not need to do this test under locking as in the worst-case
  2825. * we queue the retire worker once too often.
  2826. */
  2827. if (READ_ONCE(dev_priv->gt.awake))
  2828. queue_delayed_work(dev_priv->wq,
  2829. &dev_priv->gt.retire_work,
  2830. round_jiffies_up_relative(HZ));
  2831. }
  2832. static void shrink_caches(struct drm_i915_private *i915)
  2833. {
  2834. /*
  2835. * kmem_cache_shrink() discards empty slabs and reorders partially
  2836. * filled slabs to prioritise allocating from the mostly full slabs,
  2837. * with the aim of reducing fragmentation.
  2838. */
  2839. kmem_cache_shrink(i915->priorities);
  2840. kmem_cache_shrink(i915->dependencies);
  2841. kmem_cache_shrink(i915->requests);
  2842. kmem_cache_shrink(i915->luts);
  2843. kmem_cache_shrink(i915->vmas);
  2844. kmem_cache_shrink(i915->objects);
  2845. }
  2846. struct sleep_rcu_work {
  2847. union {
  2848. struct rcu_head rcu;
  2849. struct work_struct work;
  2850. };
  2851. struct drm_i915_private *i915;
  2852. unsigned int epoch;
  2853. };
  2854. static inline bool
  2855. same_epoch(struct drm_i915_private *i915, unsigned int epoch)
  2856. {
  2857. /*
  2858. * There is a small chance that the epoch wrapped since we started
  2859. * sleeping. If we assume that epoch is at least a u32, then it will
  2860. * take at least 2^32 * 100ms for it to wrap, or about 326 years.
  2861. */
  2862. return epoch == READ_ONCE(i915->gt.epoch);
  2863. }
  2864. static void __sleep_work(struct work_struct *work)
  2865. {
  2866. struct sleep_rcu_work *s = container_of(work, typeof(*s), work);
  2867. struct drm_i915_private *i915 = s->i915;
  2868. unsigned int epoch = s->epoch;
  2869. kfree(s);
  2870. if (same_epoch(i915, epoch))
  2871. shrink_caches(i915);
  2872. }
  2873. static void __sleep_rcu(struct rcu_head *rcu)
  2874. {
  2875. struct sleep_rcu_work *s = container_of(rcu, typeof(*s), rcu);
  2876. struct drm_i915_private *i915 = s->i915;
  2877. if (same_epoch(i915, s->epoch)) {
  2878. INIT_WORK(&s->work, __sleep_work);
  2879. queue_work(i915->wq, &s->work);
  2880. } else {
  2881. kfree(s);
  2882. }
  2883. }
  2884. static inline bool
  2885. new_requests_since_last_retire(const struct drm_i915_private *i915)
  2886. {
  2887. return (READ_ONCE(i915->gt.active_requests) ||
  2888. work_pending(&i915->gt.idle_work.work));
  2889. }
  2890. static void
  2891. i915_gem_idle_work_handler(struct work_struct *work)
  2892. {
  2893. struct drm_i915_private *dev_priv =
  2894. container_of(work, typeof(*dev_priv), gt.idle_work.work);
  2895. unsigned int epoch = I915_EPOCH_INVALID;
  2896. bool rearm_hangcheck;
  2897. if (!READ_ONCE(dev_priv->gt.awake))
  2898. return;
  2899. /*
  2900. * Wait for last execlists context complete, but bail out in case a
  2901. * new request is submitted. As we don't trust the hardware, we
  2902. * continue on if the wait times out. This is necessary to allow
  2903. * the machine to suspend even if the hardware dies, and we will
  2904. * try to recover in resume (after depriving the hardware of power,
  2905. * it may be in a better mmod).
  2906. */
  2907. __wait_for(if (new_requests_since_last_retire(dev_priv)) return,
  2908. intel_engines_are_idle(dev_priv),
  2909. I915_IDLE_ENGINES_TIMEOUT * 1000,
  2910. 10, 500);
  2911. rearm_hangcheck =
  2912. cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
  2913. if (!mutex_trylock(&dev_priv->drm.struct_mutex)) {
  2914. /* Currently busy, come back later */
  2915. mod_delayed_work(dev_priv->wq,
  2916. &dev_priv->gt.idle_work,
  2917. msecs_to_jiffies(50));
  2918. goto out_rearm;
  2919. }
  2920. /*
  2921. * New request retired after this work handler started, extend active
  2922. * period until next instance of the work.
  2923. */
  2924. if (new_requests_since_last_retire(dev_priv))
  2925. goto out_unlock;
  2926. /*
  2927. * Be paranoid and flush a concurrent interrupt to make sure
  2928. * we don't reactivate any irq tasklets after parking.
  2929. *
  2930. * FIXME: Note that even though we have waited for execlists to be idle,
  2931. * there may still be an in-flight interrupt even though the CSB
  2932. * is now empty. synchronize_irq() makes sure that a residual interrupt
  2933. * is completed before we continue, but it doesn't prevent the HW from
  2934. * raising a spurious interrupt later. To complete the shield we should
  2935. * coordinate disabling the CS irq with flushing the interrupts.
  2936. */
  2937. synchronize_irq(dev_priv->drm.irq);
  2938. intel_engines_park(dev_priv);
  2939. i915_gem_timelines_park(dev_priv);
  2940. i915_pmu_gt_parked(dev_priv);
  2941. GEM_BUG_ON(!dev_priv->gt.awake);
  2942. dev_priv->gt.awake = false;
  2943. epoch = dev_priv->gt.epoch;
  2944. GEM_BUG_ON(epoch == I915_EPOCH_INVALID);
  2945. rearm_hangcheck = false;
  2946. if (INTEL_GEN(dev_priv) >= 6)
  2947. gen6_rps_idle(dev_priv);
  2948. intel_display_power_put(dev_priv, POWER_DOMAIN_GT_IRQ);
  2949. intel_runtime_pm_put(dev_priv);
  2950. out_unlock:
  2951. mutex_unlock(&dev_priv->drm.struct_mutex);
  2952. out_rearm:
  2953. if (rearm_hangcheck) {
  2954. GEM_BUG_ON(!dev_priv->gt.awake);
  2955. i915_queue_hangcheck(dev_priv);
  2956. }
  2957. /*
  2958. * When we are idle, it is an opportune time to reap our caches.
  2959. * However, we have many objects that utilise RCU and the ordered
  2960. * i915->wq that this work is executing on. To try and flush any
  2961. * pending frees now we are idle, we first wait for an RCU grace
  2962. * period, and then queue a task (that will run last on the wq) to
  2963. * shrink and re-optimize the caches.
  2964. */
  2965. if (same_epoch(dev_priv, epoch)) {
  2966. struct sleep_rcu_work *s = kmalloc(sizeof(*s), GFP_KERNEL);
  2967. if (s) {
  2968. s->i915 = dev_priv;
  2969. s->epoch = epoch;
  2970. call_rcu(&s->rcu, __sleep_rcu);
  2971. }
  2972. }
  2973. }
  2974. void i915_gem_close_object(struct drm_gem_object *gem, struct drm_file *file)
  2975. {
  2976. struct drm_i915_private *i915 = to_i915(gem->dev);
  2977. struct drm_i915_gem_object *obj = to_intel_bo(gem);
  2978. struct drm_i915_file_private *fpriv = file->driver_priv;
  2979. struct i915_lut_handle *lut, *ln;
  2980. mutex_lock(&i915->drm.struct_mutex);
  2981. list_for_each_entry_safe(lut, ln, &obj->lut_list, obj_link) {
  2982. struct i915_gem_context *ctx = lut->ctx;
  2983. struct i915_vma *vma;
  2984. GEM_BUG_ON(ctx->file_priv == ERR_PTR(-EBADF));
  2985. if (ctx->file_priv != fpriv)
  2986. continue;
  2987. vma = radix_tree_delete(&ctx->handles_vma, lut->handle);
  2988. GEM_BUG_ON(vma->obj != obj);
  2989. /* We allow the process to have multiple handles to the same
  2990. * vma, in the same fd namespace, by virtue of flink/open.
  2991. */
  2992. GEM_BUG_ON(!vma->open_count);
  2993. if (!--vma->open_count && !i915_vma_is_ggtt(vma))
  2994. i915_vma_close(vma);
  2995. list_del(&lut->obj_link);
  2996. list_del(&lut->ctx_link);
  2997. kmem_cache_free(i915->luts, lut);
  2998. __i915_gem_object_release_unless_active(obj);
  2999. }
  3000. mutex_unlock(&i915->drm.struct_mutex);
  3001. }
  3002. static unsigned long to_wait_timeout(s64 timeout_ns)
  3003. {
  3004. if (timeout_ns < 0)
  3005. return MAX_SCHEDULE_TIMEOUT;
  3006. if (timeout_ns == 0)
  3007. return 0;
  3008. return nsecs_to_jiffies_timeout(timeout_ns);
  3009. }
  3010. /**
  3011. * i915_gem_wait_ioctl - implements DRM_IOCTL_I915_GEM_WAIT
  3012. * @dev: drm device pointer
  3013. * @data: ioctl data blob
  3014. * @file: drm file pointer
  3015. *
  3016. * Returns 0 if successful, else an error is returned with the remaining time in
  3017. * the timeout parameter.
  3018. * -ETIME: object is still busy after timeout
  3019. * -ERESTARTSYS: signal interrupted the wait
  3020. * -ENONENT: object doesn't exist
  3021. * Also possible, but rare:
  3022. * -EAGAIN: incomplete, restart syscall
  3023. * -ENOMEM: damn
  3024. * -ENODEV: Internal IRQ fail
  3025. * -E?: The add request failed
  3026. *
  3027. * The wait ioctl with a timeout of 0 reimplements the busy ioctl. With any
  3028. * non-zero timeout parameter the wait ioctl will wait for the given number of
  3029. * nanoseconds on an object becoming unbusy. Since the wait itself does so
  3030. * without holding struct_mutex the object may become re-busied before this
  3031. * function completes. A similar but shorter * race condition exists in the busy
  3032. * ioctl
  3033. */
  3034. int
  3035. i915_gem_wait_ioctl(struct drm_device *dev, void *data, struct drm_file *file)
  3036. {
  3037. struct drm_i915_gem_wait *args = data;
  3038. struct drm_i915_gem_object *obj;
  3039. ktime_t start;
  3040. long ret;
  3041. if (args->flags != 0)
  3042. return -EINVAL;
  3043. obj = i915_gem_object_lookup(file, args->bo_handle);
  3044. if (!obj)
  3045. return -ENOENT;
  3046. start = ktime_get();
  3047. ret = i915_gem_object_wait(obj,
  3048. I915_WAIT_INTERRUPTIBLE | I915_WAIT_ALL,
  3049. to_wait_timeout(args->timeout_ns),
  3050. to_rps_client(file));
  3051. if (args->timeout_ns > 0) {
  3052. args->timeout_ns -= ktime_to_ns(ktime_sub(ktime_get(), start));
  3053. if (args->timeout_ns < 0)
  3054. args->timeout_ns = 0;
  3055. /*
  3056. * Apparently ktime isn't accurate enough and occasionally has a
  3057. * bit of mismatch in the jiffies<->nsecs<->ktime loop. So patch
  3058. * things up to make the test happy. We allow up to 1 jiffy.
  3059. *
  3060. * This is a regression from the timespec->ktime conversion.
  3061. */
  3062. if (ret == -ETIME && !nsecs_to_jiffies(args->timeout_ns))
  3063. args->timeout_ns = 0;
  3064. /* Asked to wait beyond the jiffie/scheduler precision? */
  3065. if (ret == -ETIME && args->timeout_ns)
  3066. ret = -EAGAIN;
  3067. }
  3068. i915_gem_object_put(obj);
  3069. return ret;
  3070. }
  3071. static int wait_for_timeline(struct i915_gem_timeline *tl, unsigned int flags)
  3072. {
  3073. int ret, i;
  3074. for (i = 0; i < ARRAY_SIZE(tl->engine); i++) {
  3075. ret = i915_gem_active_wait(&tl->engine[i].last_request, flags);
  3076. if (ret)
  3077. return ret;
  3078. }
  3079. return 0;
  3080. }
  3081. static int wait_for_engines(struct drm_i915_private *i915)
  3082. {
  3083. if (wait_for(intel_engines_are_idle(i915), I915_IDLE_ENGINES_TIMEOUT)) {
  3084. dev_err(i915->drm.dev,
  3085. "Failed to idle engines, declaring wedged!\n");
  3086. if (drm_debug & DRM_UT_DRIVER) {
  3087. struct drm_printer p = drm_debug_printer(__func__);
  3088. struct intel_engine_cs *engine;
  3089. enum intel_engine_id id;
  3090. for_each_engine(engine, i915, id)
  3091. intel_engine_dump(engine, &p,
  3092. "%s\n", engine->name);
  3093. }
  3094. i915_gem_set_wedged(i915);
  3095. return -EIO;
  3096. }
  3097. return 0;
  3098. }
  3099. int i915_gem_wait_for_idle(struct drm_i915_private *i915, unsigned int flags)
  3100. {
  3101. int ret;
  3102. /* If the device is asleep, we have no requests outstanding */
  3103. if (!READ_ONCE(i915->gt.awake))
  3104. return 0;
  3105. if (flags & I915_WAIT_LOCKED) {
  3106. struct i915_gem_timeline *tl;
  3107. lockdep_assert_held(&i915->drm.struct_mutex);
  3108. list_for_each_entry(tl, &i915->gt.timelines, link) {
  3109. ret = wait_for_timeline(tl, flags);
  3110. if (ret)
  3111. return ret;
  3112. }
  3113. i915_retire_requests(i915);
  3114. ret = wait_for_engines(i915);
  3115. } else {
  3116. ret = wait_for_timeline(&i915->gt.global_timeline, flags);
  3117. }
  3118. return ret;
  3119. }
  3120. static void __i915_gem_object_flush_for_display(struct drm_i915_gem_object *obj)
  3121. {
  3122. /*
  3123. * We manually flush the CPU domain so that we can override and
  3124. * force the flush for the display, and perform it asyncrhonously.
  3125. */
  3126. flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
  3127. if (obj->cache_dirty)
  3128. i915_gem_clflush_object(obj, I915_CLFLUSH_FORCE);
  3129. obj->write_domain = 0;
  3130. }
  3131. void i915_gem_object_flush_if_display(struct drm_i915_gem_object *obj)
  3132. {
  3133. if (!READ_ONCE(obj->pin_global))
  3134. return;
  3135. mutex_lock(&obj->base.dev->struct_mutex);
  3136. __i915_gem_object_flush_for_display(obj);
  3137. mutex_unlock(&obj->base.dev->struct_mutex);
  3138. }
  3139. /**
  3140. * Moves a single object to the WC read, and possibly write domain.
  3141. * @obj: object to act on
  3142. * @write: ask for write access or read only
  3143. *
  3144. * This function returns when the move is complete, including waiting on
  3145. * flushes to occur.
  3146. */
  3147. int
  3148. i915_gem_object_set_to_wc_domain(struct drm_i915_gem_object *obj, bool write)
  3149. {
  3150. int ret;
  3151. lockdep_assert_held(&obj->base.dev->struct_mutex);
  3152. ret = i915_gem_object_wait(obj,
  3153. I915_WAIT_INTERRUPTIBLE |
  3154. I915_WAIT_LOCKED |
  3155. (write ? I915_WAIT_ALL : 0),
  3156. MAX_SCHEDULE_TIMEOUT,
  3157. NULL);
  3158. if (ret)
  3159. return ret;
  3160. if (obj->write_domain == I915_GEM_DOMAIN_WC)
  3161. return 0;
  3162. /* Flush and acquire obj->pages so that we are coherent through
  3163. * direct access in memory with previous cached writes through
  3164. * shmemfs and that our cache domain tracking remains valid.
  3165. * For example, if the obj->filp was moved to swap without us
  3166. * being notified and releasing the pages, we would mistakenly
  3167. * continue to assume that the obj remained out of the CPU cached
  3168. * domain.
  3169. */
  3170. ret = i915_gem_object_pin_pages(obj);
  3171. if (ret)
  3172. return ret;
  3173. flush_write_domain(obj, ~I915_GEM_DOMAIN_WC);
  3174. /* Serialise direct access to this object with the barriers for
  3175. * coherent writes from the GPU, by effectively invalidating the
  3176. * WC domain upon first access.
  3177. */
  3178. if ((obj->read_domains & I915_GEM_DOMAIN_WC) == 0)
  3179. mb();
  3180. /* It should now be out of any other write domains, and we can update
  3181. * the domain values for our changes.
  3182. */
  3183. GEM_BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_WC) != 0);
  3184. obj->read_domains |= I915_GEM_DOMAIN_WC;
  3185. if (write) {
  3186. obj->read_domains = I915_GEM_DOMAIN_WC;
  3187. obj->write_domain = I915_GEM_DOMAIN_WC;
  3188. obj->mm.dirty = true;
  3189. }
  3190. i915_gem_object_unpin_pages(obj);
  3191. return 0;
  3192. }
  3193. /**
  3194. * Moves a single object to the GTT read, and possibly write domain.
  3195. * @obj: object to act on
  3196. * @write: ask for write access or read only
  3197. *
  3198. * This function returns when the move is complete, including waiting on
  3199. * flushes to occur.
  3200. */
  3201. int
  3202. i915_gem_object_set_to_gtt_domain(struct drm_i915_gem_object *obj, bool write)
  3203. {
  3204. int ret;
  3205. lockdep_assert_held(&obj->base.dev->struct_mutex);
  3206. ret = i915_gem_object_wait(obj,
  3207. I915_WAIT_INTERRUPTIBLE |
  3208. I915_WAIT_LOCKED |
  3209. (write ? I915_WAIT_ALL : 0),
  3210. MAX_SCHEDULE_TIMEOUT,
  3211. NULL);
  3212. if (ret)
  3213. return ret;
  3214. if (obj->write_domain == I915_GEM_DOMAIN_GTT)
  3215. return 0;
  3216. /* Flush and acquire obj->pages so that we are coherent through
  3217. * direct access in memory with previous cached writes through
  3218. * shmemfs and that our cache domain tracking remains valid.
  3219. * For example, if the obj->filp was moved to swap without us
  3220. * being notified and releasing the pages, we would mistakenly
  3221. * continue to assume that the obj remained out of the CPU cached
  3222. * domain.
  3223. */
  3224. ret = i915_gem_object_pin_pages(obj);
  3225. if (ret)
  3226. return ret;
  3227. flush_write_domain(obj, ~I915_GEM_DOMAIN_GTT);
  3228. /* Serialise direct access to this object with the barriers for
  3229. * coherent writes from the GPU, by effectively invalidating the
  3230. * GTT domain upon first access.
  3231. */
  3232. if ((obj->read_domains & I915_GEM_DOMAIN_GTT) == 0)
  3233. mb();
  3234. /* It should now be out of any other write domains, and we can update
  3235. * the domain values for our changes.
  3236. */
  3237. GEM_BUG_ON((obj->write_domain & ~I915_GEM_DOMAIN_GTT) != 0);
  3238. obj->read_domains |= I915_GEM_DOMAIN_GTT;
  3239. if (write) {
  3240. obj->read_domains = I915_GEM_DOMAIN_GTT;
  3241. obj->write_domain = I915_GEM_DOMAIN_GTT;
  3242. obj->mm.dirty = true;
  3243. }
  3244. i915_gem_object_unpin_pages(obj);
  3245. return 0;
  3246. }
  3247. /**
  3248. * Changes the cache-level of an object across all VMA.
  3249. * @obj: object to act on
  3250. * @cache_level: new cache level to set for the object
  3251. *
  3252. * After this function returns, the object will be in the new cache-level
  3253. * across all GTT and the contents of the backing storage will be coherent,
  3254. * with respect to the new cache-level. In order to keep the backing storage
  3255. * coherent for all users, we only allow a single cache level to be set
  3256. * globally on the object and prevent it from being changed whilst the
  3257. * hardware is reading from the object. That is if the object is currently
  3258. * on the scanout it will be set to uncached (or equivalent display
  3259. * cache coherency) and all non-MOCS GPU access will also be uncached so
  3260. * that all direct access to the scanout remains coherent.
  3261. */
  3262. int i915_gem_object_set_cache_level(struct drm_i915_gem_object *obj,
  3263. enum i915_cache_level cache_level)
  3264. {
  3265. struct i915_vma *vma;
  3266. int ret;
  3267. lockdep_assert_held(&obj->base.dev->struct_mutex);
  3268. if (obj->cache_level == cache_level)
  3269. return 0;
  3270. /* Inspect the list of currently bound VMA and unbind any that would
  3271. * be invalid given the new cache-level. This is principally to
  3272. * catch the issue of the CS prefetch crossing page boundaries and
  3273. * reading an invalid PTE on older architectures.
  3274. */
  3275. restart:
  3276. list_for_each_entry(vma, &obj->vma_list, obj_link) {
  3277. if (!drm_mm_node_allocated(&vma->node))
  3278. continue;
  3279. if (i915_vma_is_pinned(vma)) {
  3280. DRM_DEBUG("can not change the cache level of pinned objects\n");
  3281. return -EBUSY;
  3282. }
  3283. if (!i915_vma_is_closed(vma) &&
  3284. i915_gem_valid_gtt_space(vma, cache_level))
  3285. continue;
  3286. ret = i915_vma_unbind(vma);
  3287. if (ret)
  3288. return ret;
  3289. /* As unbinding may affect other elements in the
  3290. * obj->vma_list (due to side-effects from retiring
  3291. * an active vma), play safe and restart the iterator.
  3292. */
  3293. goto restart;
  3294. }
  3295. /* We can reuse the existing drm_mm nodes but need to change the
  3296. * cache-level on the PTE. We could simply unbind them all and
  3297. * rebind with the correct cache-level on next use. However since
  3298. * we already have a valid slot, dma mapping, pages etc, we may as
  3299. * rewrite the PTE in the belief that doing so tramples upon less
  3300. * state and so involves less work.
  3301. */
  3302. if (obj->bind_count) {
  3303. /* Before we change the PTE, the GPU must not be accessing it.
  3304. * If we wait upon the object, we know that all the bound
  3305. * VMA are no longer active.
  3306. */
  3307. ret = i915_gem_object_wait(obj,
  3308. I915_WAIT_INTERRUPTIBLE |
  3309. I915_WAIT_LOCKED |
  3310. I915_WAIT_ALL,
  3311. MAX_SCHEDULE_TIMEOUT,
  3312. NULL);
  3313. if (ret)
  3314. return ret;
  3315. if (!HAS_LLC(to_i915(obj->base.dev)) &&
  3316. cache_level != I915_CACHE_NONE) {
  3317. /* Access to snoopable pages through the GTT is
  3318. * incoherent and on some machines causes a hard
  3319. * lockup. Relinquish the CPU mmaping to force
  3320. * userspace to refault in the pages and we can
  3321. * then double check if the GTT mapping is still
  3322. * valid for that pointer access.
  3323. */
  3324. i915_gem_release_mmap(obj);
  3325. /* As we no longer need a fence for GTT access,
  3326. * we can relinquish it now (and so prevent having
  3327. * to steal a fence from someone else on the next
  3328. * fence request). Note GPU activity would have
  3329. * dropped the fence as all snoopable access is
  3330. * supposed to be linear.
  3331. */
  3332. for_each_ggtt_vma(vma, obj) {
  3333. ret = i915_vma_put_fence(vma);
  3334. if (ret)
  3335. return ret;
  3336. }
  3337. } else {
  3338. /* We either have incoherent backing store and
  3339. * so no GTT access or the architecture is fully
  3340. * coherent. In such cases, existing GTT mmaps
  3341. * ignore the cache bit in the PTE and we can
  3342. * rewrite it without confusing the GPU or having
  3343. * to force userspace to fault back in its mmaps.
  3344. */
  3345. }
  3346. list_for_each_entry(vma, &obj->vma_list, obj_link) {
  3347. if (!drm_mm_node_allocated(&vma->node))
  3348. continue;
  3349. ret = i915_vma_bind(vma, cache_level, PIN_UPDATE);
  3350. if (ret)
  3351. return ret;
  3352. }
  3353. }
  3354. list_for_each_entry(vma, &obj->vma_list, obj_link)
  3355. vma->node.color = cache_level;
  3356. i915_gem_object_set_cache_coherency(obj, cache_level);
  3357. obj->cache_dirty = true; /* Always invalidate stale cachelines */
  3358. return 0;
  3359. }
  3360. int i915_gem_get_caching_ioctl(struct drm_device *dev, void *data,
  3361. struct drm_file *file)
  3362. {
  3363. struct drm_i915_gem_caching *args = data;
  3364. struct drm_i915_gem_object *obj;
  3365. int err = 0;
  3366. rcu_read_lock();
  3367. obj = i915_gem_object_lookup_rcu(file, args->handle);
  3368. if (!obj) {
  3369. err = -ENOENT;
  3370. goto out;
  3371. }
  3372. switch (obj->cache_level) {
  3373. case I915_CACHE_LLC:
  3374. case I915_CACHE_L3_LLC:
  3375. args->caching = I915_CACHING_CACHED;
  3376. break;
  3377. case I915_CACHE_WT:
  3378. args->caching = I915_CACHING_DISPLAY;
  3379. break;
  3380. default:
  3381. args->caching = I915_CACHING_NONE;
  3382. break;
  3383. }
  3384. out:
  3385. rcu_read_unlock();
  3386. return err;
  3387. }
  3388. int i915_gem_set_caching_ioctl(struct drm_device *dev, void *data,
  3389. struct drm_file *file)
  3390. {
  3391. struct drm_i915_private *i915 = to_i915(dev);
  3392. struct drm_i915_gem_caching *args = data;
  3393. struct drm_i915_gem_object *obj;
  3394. enum i915_cache_level level;
  3395. int ret = 0;
  3396. switch (args->caching) {
  3397. case I915_CACHING_NONE:
  3398. level = I915_CACHE_NONE;
  3399. break;
  3400. case I915_CACHING_CACHED:
  3401. /*
  3402. * Due to a HW issue on BXT A stepping, GPU stores via a
  3403. * snooped mapping may leave stale data in a corresponding CPU
  3404. * cacheline, whereas normally such cachelines would get
  3405. * invalidated.
  3406. */
  3407. if (!HAS_LLC(i915) && !HAS_SNOOP(i915))
  3408. return -ENODEV;
  3409. level = I915_CACHE_LLC;
  3410. break;
  3411. case I915_CACHING_DISPLAY:
  3412. level = HAS_WT(i915) ? I915_CACHE_WT : I915_CACHE_NONE;
  3413. break;
  3414. default:
  3415. return -EINVAL;
  3416. }
  3417. obj = i915_gem_object_lookup(file, args->handle);
  3418. if (!obj)
  3419. return -ENOENT;
  3420. /*
  3421. * The caching mode of proxy object is handled by its generator, and
  3422. * not allowed to be changed by userspace.
  3423. */
  3424. if (i915_gem_object_is_proxy(obj)) {
  3425. ret = -ENXIO;
  3426. goto out;
  3427. }
  3428. if (obj->cache_level == level)
  3429. goto out;
  3430. ret = i915_gem_object_wait(obj,
  3431. I915_WAIT_INTERRUPTIBLE,
  3432. MAX_SCHEDULE_TIMEOUT,
  3433. to_rps_client(file));
  3434. if (ret)
  3435. goto out;
  3436. ret = i915_mutex_lock_interruptible(dev);
  3437. if (ret)
  3438. goto out;
  3439. ret = i915_gem_object_set_cache_level(obj, level);
  3440. mutex_unlock(&dev->struct_mutex);
  3441. out:
  3442. i915_gem_object_put(obj);
  3443. return ret;
  3444. }
  3445. /*
  3446. * Prepare buffer for display plane (scanout, cursors, etc).
  3447. * Can be called from an uninterruptible phase (modesetting) and allows
  3448. * any flushes to be pipelined (for pageflips).
  3449. */
  3450. struct i915_vma *
  3451. i915_gem_object_pin_to_display_plane(struct drm_i915_gem_object *obj,
  3452. u32 alignment,
  3453. const struct i915_ggtt_view *view,
  3454. unsigned int flags)
  3455. {
  3456. struct i915_vma *vma;
  3457. int ret;
  3458. lockdep_assert_held(&obj->base.dev->struct_mutex);
  3459. /* Mark the global pin early so that we account for the
  3460. * display coherency whilst setting up the cache domains.
  3461. */
  3462. obj->pin_global++;
  3463. /* The display engine is not coherent with the LLC cache on gen6. As
  3464. * a result, we make sure that the pinning that is about to occur is
  3465. * done with uncached PTEs. This is lowest common denominator for all
  3466. * chipsets.
  3467. *
  3468. * However for gen6+, we could do better by using the GFDT bit instead
  3469. * of uncaching, which would allow us to flush all the LLC-cached data
  3470. * with that bit in the PTE to main memory with just one PIPE_CONTROL.
  3471. */
  3472. ret = i915_gem_object_set_cache_level(obj,
  3473. HAS_WT(to_i915(obj->base.dev)) ?
  3474. I915_CACHE_WT : I915_CACHE_NONE);
  3475. if (ret) {
  3476. vma = ERR_PTR(ret);
  3477. goto err_unpin_global;
  3478. }
  3479. /* As the user may map the buffer once pinned in the display plane
  3480. * (e.g. libkms for the bootup splash), we have to ensure that we
  3481. * always use map_and_fenceable for all scanout buffers. However,
  3482. * it may simply be too big to fit into mappable, in which case
  3483. * put it anyway and hope that userspace can cope (but always first
  3484. * try to preserve the existing ABI).
  3485. */
  3486. vma = ERR_PTR(-ENOSPC);
  3487. if ((flags & PIN_MAPPABLE) == 0 &&
  3488. (!view || view->type == I915_GGTT_VIEW_NORMAL))
  3489. vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment,
  3490. flags |
  3491. PIN_MAPPABLE |
  3492. PIN_NONBLOCK);
  3493. if (IS_ERR(vma))
  3494. vma = i915_gem_object_ggtt_pin(obj, view, 0, alignment, flags);
  3495. if (IS_ERR(vma))
  3496. goto err_unpin_global;
  3497. vma->display_alignment = max_t(u64, vma->display_alignment, alignment);
  3498. /* Treat this as an end-of-frame, like intel_user_framebuffer_dirty() */
  3499. __i915_gem_object_flush_for_display(obj);
  3500. intel_fb_obj_flush(obj, ORIGIN_DIRTYFB);
  3501. /* It should now be out of any other write domains, and we can update
  3502. * the domain values for our changes.
  3503. */
  3504. obj->read_domains |= I915_GEM_DOMAIN_GTT;
  3505. return vma;
  3506. err_unpin_global:
  3507. obj->pin_global--;
  3508. return vma;
  3509. }
  3510. void
  3511. i915_gem_object_unpin_from_display_plane(struct i915_vma *vma)
  3512. {
  3513. lockdep_assert_held(&vma->vm->i915->drm.struct_mutex);
  3514. if (WARN_ON(vma->obj->pin_global == 0))
  3515. return;
  3516. if (--vma->obj->pin_global == 0)
  3517. vma->display_alignment = I915_GTT_MIN_ALIGNMENT;
  3518. /* Bump the LRU to try and avoid premature eviction whilst flipping */
  3519. i915_gem_object_bump_inactive_ggtt(vma->obj);
  3520. i915_vma_unpin(vma);
  3521. }
  3522. /**
  3523. * Moves a single object to the CPU read, and possibly write domain.
  3524. * @obj: object to act on
  3525. * @write: requesting write or read-only access
  3526. *
  3527. * This function returns when the move is complete, including waiting on
  3528. * flushes to occur.
  3529. */
  3530. int
  3531. i915_gem_object_set_to_cpu_domain(struct drm_i915_gem_object *obj, bool write)
  3532. {
  3533. int ret;
  3534. lockdep_assert_held(&obj->base.dev->struct_mutex);
  3535. ret = i915_gem_object_wait(obj,
  3536. I915_WAIT_INTERRUPTIBLE |
  3537. I915_WAIT_LOCKED |
  3538. (write ? I915_WAIT_ALL : 0),
  3539. MAX_SCHEDULE_TIMEOUT,
  3540. NULL);
  3541. if (ret)
  3542. return ret;
  3543. flush_write_domain(obj, ~I915_GEM_DOMAIN_CPU);
  3544. /* Flush the CPU cache if it's still invalid. */
  3545. if ((obj->read_domains & I915_GEM_DOMAIN_CPU) == 0) {
  3546. i915_gem_clflush_object(obj, I915_CLFLUSH_SYNC);
  3547. obj->read_domains |= I915_GEM_DOMAIN_CPU;
  3548. }
  3549. /* It should now be out of any other write domains, and we can update
  3550. * the domain values for our changes.
  3551. */
  3552. GEM_BUG_ON(obj->write_domain & ~I915_GEM_DOMAIN_CPU);
  3553. /* If we're writing through the CPU, then the GPU read domains will
  3554. * need to be invalidated at next use.
  3555. */
  3556. if (write)
  3557. __start_cpu_write(obj);
  3558. return 0;
  3559. }
  3560. /* Throttle our rendering by waiting until the ring has completed our requests
  3561. * emitted over 20 msec ago.
  3562. *
  3563. * Note that if we were to use the current jiffies each time around the loop,
  3564. * we wouldn't escape the function with any frames outstanding if the time to
  3565. * render a frame was over 20ms.
  3566. *
  3567. * This should get us reasonable parallelism between CPU and GPU but also
  3568. * relatively low latency when blocking on a particular request to finish.
  3569. */
  3570. static int
  3571. i915_gem_ring_throttle(struct drm_device *dev, struct drm_file *file)
  3572. {
  3573. struct drm_i915_private *dev_priv = to_i915(dev);
  3574. struct drm_i915_file_private *file_priv = file->driver_priv;
  3575. unsigned long recent_enough = jiffies - DRM_I915_THROTTLE_JIFFIES;
  3576. struct i915_request *request, *target = NULL;
  3577. long ret;
  3578. /* ABI: return -EIO if already wedged */
  3579. if (i915_terminally_wedged(&dev_priv->gpu_error))
  3580. return -EIO;
  3581. spin_lock(&file_priv->mm.lock);
  3582. list_for_each_entry(request, &file_priv->mm.request_list, client_link) {
  3583. if (time_after_eq(request->emitted_jiffies, recent_enough))
  3584. break;
  3585. if (target) {
  3586. list_del(&target->client_link);
  3587. target->file_priv = NULL;
  3588. }
  3589. target = request;
  3590. }
  3591. if (target)
  3592. i915_request_get(target);
  3593. spin_unlock(&file_priv->mm.lock);
  3594. if (target == NULL)
  3595. return 0;
  3596. ret = i915_request_wait(target,
  3597. I915_WAIT_INTERRUPTIBLE,
  3598. MAX_SCHEDULE_TIMEOUT);
  3599. i915_request_put(target);
  3600. return ret < 0 ? ret : 0;
  3601. }
  3602. struct i915_vma *
  3603. i915_gem_object_ggtt_pin(struct drm_i915_gem_object *obj,
  3604. const struct i915_ggtt_view *view,
  3605. u64 size,
  3606. u64 alignment,
  3607. u64 flags)
  3608. {
  3609. struct drm_i915_private *dev_priv = to_i915(obj->base.dev);
  3610. struct i915_address_space *vm = &dev_priv->ggtt.base;
  3611. struct i915_vma *vma;
  3612. int ret;
  3613. lockdep_assert_held(&obj->base.dev->struct_mutex);
  3614. if (flags & PIN_MAPPABLE &&
  3615. (!view || view->type == I915_GGTT_VIEW_NORMAL)) {
  3616. /* If the required space is larger than the available
  3617. * aperture, we will not able to find a slot for the
  3618. * object and unbinding the object now will be in
  3619. * vain. Worse, doing so may cause us to ping-pong
  3620. * the object in and out of the Global GTT and
  3621. * waste a lot of cycles under the mutex.
  3622. */
  3623. if (obj->base.size > dev_priv->ggtt.mappable_end)
  3624. return ERR_PTR(-E2BIG);
  3625. /* If NONBLOCK is set the caller is optimistically
  3626. * trying to cache the full object within the mappable
  3627. * aperture, and *must* have a fallback in place for
  3628. * situations where we cannot bind the object. We
  3629. * can be a little more lax here and use the fallback
  3630. * more often to avoid costly migrations of ourselves
  3631. * and other objects within the aperture.
  3632. *
  3633. * Half-the-aperture is used as a simple heuristic.
  3634. * More interesting would to do search for a free
  3635. * block prior to making the commitment to unbind.
  3636. * That caters for the self-harm case, and with a
  3637. * little more heuristics (e.g. NOFAULT, NOEVICT)
  3638. * we could try to minimise harm to others.
  3639. */
  3640. if (flags & PIN_NONBLOCK &&
  3641. obj->base.size > dev_priv->ggtt.mappable_end / 2)
  3642. return ERR_PTR(-ENOSPC);
  3643. }
  3644. vma = i915_vma_instance(obj, vm, view);
  3645. if (unlikely(IS_ERR(vma)))
  3646. return vma;
  3647. if (i915_vma_misplaced(vma, size, alignment, flags)) {
  3648. if (flags & PIN_NONBLOCK) {
  3649. if (i915_vma_is_pinned(vma) || i915_vma_is_active(vma))
  3650. return ERR_PTR(-ENOSPC);
  3651. if (flags & PIN_MAPPABLE &&
  3652. vma->fence_size > dev_priv->ggtt.mappable_end / 2)
  3653. return ERR_PTR(-ENOSPC);
  3654. }
  3655. WARN(i915_vma_is_pinned(vma),
  3656. "bo is already pinned in ggtt with incorrect alignment:"
  3657. " offset=%08x, req.alignment=%llx,"
  3658. " req.map_and_fenceable=%d, vma->map_and_fenceable=%d\n",
  3659. i915_ggtt_offset(vma), alignment,
  3660. !!(flags & PIN_MAPPABLE),
  3661. i915_vma_is_map_and_fenceable(vma));
  3662. ret = i915_vma_unbind(vma);
  3663. if (ret)
  3664. return ERR_PTR(ret);
  3665. }
  3666. ret = i915_vma_pin(vma, size, alignment, flags | PIN_GLOBAL);
  3667. if (ret)
  3668. return ERR_PTR(ret);
  3669. return vma;
  3670. }
  3671. static __always_inline unsigned int __busy_read_flag(unsigned int id)
  3672. {
  3673. /* Note that we could alias engines in the execbuf API, but
  3674. * that would be very unwise as it prevents userspace from
  3675. * fine control over engine selection. Ahem.
  3676. *
  3677. * This should be something like EXEC_MAX_ENGINE instead of
  3678. * I915_NUM_ENGINES.
  3679. */
  3680. BUILD_BUG_ON(I915_NUM_ENGINES > 16);
  3681. return 0x10000 << id;
  3682. }
  3683. static __always_inline unsigned int __busy_write_id(unsigned int id)
  3684. {
  3685. /* The uABI guarantees an active writer is also amongst the read
  3686. * engines. This would be true if we accessed the activity tracking
  3687. * under the lock, but as we perform the lookup of the object and
  3688. * its activity locklessly we can not guarantee that the last_write
  3689. * being active implies that we have set the same engine flag from
  3690. * last_read - hence we always set both read and write busy for
  3691. * last_write.
  3692. */
  3693. return id | __busy_read_flag(id);
  3694. }
  3695. static __always_inline unsigned int
  3696. __busy_set_if_active(const struct dma_fence *fence,
  3697. unsigned int (*flag)(unsigned int id))
  3698. {
  3699. struct i915_request *rq;
  3700. /* We have to check the current hw status of the fence as the uABI
  3701. * guarantees forward progress. We could rely on the idle worker
  3702. * to eventually flush us, but to minimise latency just ask the
  3703. * hardware.
  3704. *
  3705. * Note we only report on the status of native fences.
  3706. */
  3707. if (!dma_fence_is_i915(fence))
  3708. return 0;
  3709. /* opencode to_request() in order to avoid const warnings */
  3710. rq = container_of(fence, struct i915_request, fence);
  3711. if (i915_request_completed(rq))
  3712. return 0;
  3713. return flag(rq->engine->uabi_id);
  3714. }
  3715. static __always_inline unsigned int
  3716. busy_check_reader(const struct dma_fence *fence)
  3717. {
  3718. return __busy_set_if_active(fence, __busy_read_flag);
  3719. }
  3720. static __always_inline unsigned int
  3721. busy_check_writer(const struct dma_fence *fence)
  3722. {
  3723. if (!fence)
  3724. return 0;
  3725. return __busy_set_if_active(fence, __busy_write_id);
  3726. }
  3727. int
  3728. i915_gem_busy_ioctl(struct drm_device *dev, void *data,
  3729. struct drm_file *file)
  3730. {
  3731. struct drm_i915_gem_busy *args = data;
  3732. struct drm_i915_gem_object *obj;
  3733. struct reservation_object_list *list;
  3734. unsigned int seq;
  3735. int err;
  3736. err = -ENOENT;
  3737. rcu_read_lock();
  3738. obj = i915_gem_object_lookup_rcu(file, args->handle);
  3739. if (!obj)
  3740. goto out;
  3741. /* A discrepancy here is that we do not report the status of
  3742. * non-i915 fences, i.e. even though we may report the object as idle,
  3743. * a call to set-domain may still stall waiting for foreign rendering.
  3744. * This also means that wait-ioctl may report an object as busy,
  3745. * where busy-ioctl considers it idle.
  3746. *
  3747. * We trade the ability to warn of foreign fences to report on which
  3748. * i915 engines are active for the object.
  3749. *
  3750. * Alternatively, we can trade that extra information on read/write
  3751. * activity with
  3752. * args->busy =
  3753. * !reservation_object_test_signaled_rcu(obj->resv, true);
  3754. * to report the overall busyness. This is what the wait-ioctl does.
  3755. *
  3756. */
  3757. retry:
  3758. seq = raw_read_seqcount(&obj->resv->seq);
  3759. /* Translate the exclusive fence to the READ *and* WRITE engine */
  3760. args->busy = busy_check_writer(rcu_dereference(obj->resv->fence_excl));
  3761. /* Translate shared fences to READ set of engines */
  3762. list = rcu_dereference(obj->resv->fence);
  3763. if (list) {
  3764. unsigned int shared_count = list->shared_count, i;
  3765. for (i = 0; i < shared_count; ++i) {
  3766. struct dma_fence *fence =
  3767. rcu_dereference(list->shared[i]);
  3768. args->busy |= busy_check_reader(fence);
  3769. }
  3770. }
  3771. if (args->busy && read_seqcount_retry(&obj->resv->seq, seq))
  3772. goto retry;
  3773. err = 0;
  3774. out:
  3775. rcu_read_unlock();
  3776. return err;
  3777. }
  3778. int
  3779. i915_gem_throttle_ioctl(struct drm_device *dev, void *data,
  3780. struct drm_file *file_priv)
  3781. {
  3782. return i915_gem_ring_throttle(dev, file_priv);
  3783. }
  3784. int
  3785. i915_gem_madvise_ioctl(struct drm_device *dev, void *data,
  3786. struct drm_file *file_priv)
  3787. {
  3788. struct drm_i915_private *dev_priv = to_i915(dev);
  3789. struct drm_i915_gem_madvise *args = data;
  3790. struct drm_i915_gem_object *obj;
  3791. int err;
  3792. switch (args->madv) {
  3793. case I915_MADV_DONTNEED:
  3794. case I915_MADV_WILLNEED:
  3795. break;
  3796. default:
  3797. return -EINVAL;
  3798. }
  3799. obj = i915_gem_object_lookup(file_priv, args->handle);
  3800. if (!obj)
  3801. return -ENOENT;
  3802. err = mutex_lock_interruptible(&obj->mm.lock);
  3803. if (err)
  3804. goto out;
  3805. if (i915_gem_object_has_pages(obj) &&
  3806. i915_gem_object_is_tiled(obj) &&
  3807. dev_priv->quirks & QUIRK_PIN_SWIZZLED_PAGES) {
  3808. if (obj->mm.madv == I915_MADV_WILLNEED) {
  3809. GEM_BUG_ON(!obj->mm.quirked);
  3810. __i915_gem_object_unpin_pages(obj);
  3811. obj->mm.quirked = false;
  3812. }
  3813. if (args->madv == I915_MADV_WILLNEED) {
  3814. GEM_BUG_ON(obj->mm.quirked);
  3815. __i915_gem_object_pin_pages(obj);
  3816. obj->mm.quirked = true;
  3817. }
  3818. }
  3819. if (obj->mm.madv != __I915_MADV_PURGED)
  3820. obj->mm.madv = args->madv;
  3821. /* if the object is no longer attached, discard its backing storage */
  3822. if (obj->mm.madv == I915_MADV_DONTNEED &&
  3823. !i915_gem_object_has_pages(obj))
  3824. i915_gem_object_truncate(obj);
  3825. args->retained = obj->mm.madv != __I915_MADV_PURGED;
  3826. mutex_unlock(&obj->mm.lock);
  3827. out:
  3828. i915_gem_object_put(obj);
  3829. return err;
  3830. }
  3831. static void
  3832. frontbuffer_retire(struct i915_gem_active *active, struct i915_request *request)
  3833. {
  3834. struct drm_i915_gem_object *obj =
  3835. container_of(active, typeof(*obj), frontbuffer_write);
  3836. intel_fb_obj_flush(obj, ORIGIN_CS);
  3837. }
  3838. void i915_gem_object_init(struct drm_i915_gem_object *obj,
  3839. const struct drm_i915_gem_object_ops *ops)
  3840. {
  3841. mutex_init(&obj->mm.lock);
  3842. INIT_LIST_HEAD(&obj->vma_list);
  3843. INIT_LIST_HEAD(&obj->lut_list);
  3844. INIT_LIST_HEAD(&obj->batch_pool_link);
  3845. obj->ops = ops;
  3846. reservation_object_init(&obj->__builtin_resv);
  3847. obj->resv = &obj->__builtin_resv;
  3848. obj->frontbuffer_ggtt_origin = ORIGIN_GTT;
  3849. init_request_active(&obj->frontbuffer_write, frontbuffer_retire);
  3850. obj->mm.madv = I915_MADV_WILLNEED;
  3851. INIT_RADIX_TREE(&obj->mm.get_page.radix, GFP_KERNEL | __GFP_NOWARN);
  3852. mutex_init(&obj->mm.get_page.lock);
  3853. i915_gem_info_add_obj(to_i915(obj->base.dev), obj->base.size);
  3854. }
  3855. static const struct drm_i915_gem_object_ops i915_gem_object_ops = {
  3856. .flags = I915_GEM_OBJECT_HAS_STRUCT_PAGE |
  3857. I915_GEM_OBJECT_IS_SHRINKABLE,
  3858. .get_pages = i915_gem_object_get_pages_gtt,
  3859. .put_pages = i915_gem_object_put_pages_gtt,
  3860. .pwrite = i915_gem_object_pwrite_gtt,
  3861. };
  3862. static int i915_gem_object_create_shmem(struct drm_device *dev,
  3863. struct drm_gem_object *obj,
  3864. size_t size)
  3865. {
  3866. struct drm_i915_private *i915 = to_i915(dev);
  3867. unsigned long flags = VM_NORESERVE;
  3868. struct file *filp;
  3869. drm_gem_private_object_init(dev, obj, size);
  3870. if (i915->mm.gemfs)
  3871. filp = shmem_file_setup_with_mnt(i915->mm.gemfs, "i915", size,
  3872. flags);
  3873. else
  3874. filp = shmem_file_setup("i915", size, flags);
  3875. if (IS_ERR(filp))
  3876. return PTR_ERR(filp);
  3877. obj->filp = filp;
  3878. return 0;
  3879. }
  3880. struct drm_i915_gem_object *
  3881. i915_gem_object_create(struct drm_i915_private *dev_priv, u64 size)
  3882. {
  3883. struct drm_i915_gem_object *obj;
  3884. struct address_space *mapping;
  3885. unsigned int cache_level;
  3886. gfp_t mask;
  3887. int ret;
  3888. /* There is a prevalence of the assumption that we fit the object's
  3889. * page count inside a 32bit _signed_ variable. Let's document this and
  3890. * catch if we ever need to fix it. In the meantime, if you do spot
  3891. * such a local variable, please consider fixing!
  3892. */
  3893. if (size >> PAGE_SHIFT > INT_MAX)
  3894. return ERR_PTR(-E2BIG);
  3895. if (overflows_type(size, obj->base.size))
  3896. return ERR_PTR(-E2BIG);
  3897. obj = i915_gem_object_alloc(dev_priv);
  3898. if (obj == NULL)
  3899. return ERR_PTR(-ENOMEM);
  3900. ret = i915_gem_object_create_shmem(&dev_priv->drm, &obj->base, size);
  3901. if (ret)
  3902. goto fail;
  3903. mask = GFP_HIGHUSER | __GFP_RECLAIMABLE;
  3904. if (IS_I965GM(dev_priv) || IS_I965G(dev_priv)) {
  3905. /* 965gm cannot relocate objects above 4GiB. */
  3906. mask &= ~__GFP_HIGHMEM;
  3907. mask |= __GFP_DMA32;
  3908. }
  3909. mapping = obj->base.filp->f_mapping;
  3910. mapping_set_gfp_mask(mapping, mask);
  3911. GEM_BUG_ON(!(mapping_gfp_mask(mapping) & __GFP_RECLAIM));
  3912. i915_gem_object_init(obj, &i915_gem_object_ops);
  3913. obj->write_domain = I915_GEM_DOMAIN_CPU;
  3914. obj->read_domains = I915_GEM_DOMAIN_CPU;
  3915. if (HAS_LLC(dev_priv))
  3916. /* On some devices, we can have the GPU use the LLC (the CPU
  3917. * cache) for about a 10% performance improvement
  3918. * compared to uncached. Graphics requests other than
  3919. * display scanout are coherent with the CPU in
  3920. * accessing this cache. This means in this mode we
  3921. * don't need to clflush on the CPU side, and on the
  3922. * GPU side we only need to flush internal caches to
  3923. * get data visible to the CPU.
  3924. *
  3925. * However, we maintain the display planes as UC, and so
  3926. * need to rebind when first used as such.
  3927. */
  3928. cache_level = I915_CACHE_LLC;
  3929. else
  3930. cache_level = I915_CACHE_NONE;
  3931. i915_gem_object_set_cache_coherency(obj, cache_level);
  3932. trace_i915_gem_object_create(obj);
  3933. return obj;
  3934. fail:
  3935. i915_gem_object_free(obj);
  3936. return ERR_PTR(ret);
  3937. }
  3938. static bool discard_backing_storage(struct drm_i915_gem_object *obj)
  3939. {
  3940. /* If we are the last user of the backing storage (be it shmemfs
  3941. * pages or stolen etc), we know that the pages are going to be
  3942. * immediately released. In this case, we can then skip copying
  3943. * back the contents from the GPU.
  3944. */
  3945. if (obj->mm.madv != I915_MADV_WILLNEED)
  3946. return false;
  3947. if (obj->base.filp == NULL)
  3948. return true;
  3949. /* At first glance, this looks racy, but then again so would be
  3950. * userspace racing mmap against close. However, the first external
  3951. * reference to the filp can only be obtained through the
  3952. * i915_gem_mmap_ioctl() which safeguards us against the user
  3953. * acquiring such a reference whilst we are in the middle of
  3954. * freeing the object.
  3955. */
  3956. return atomic_long_read(&obj->base.filp->f_count) == 1;
  3957. }
  3958. static void __i915_gem_free_objects(struct drm_i915_private *i915,
  3959. struct llist_node *freed)
  3960. {
  3961. struct drm_i915_gem_object *obj, *on;
  3962. intel_runtime_pm_get(i915);
  3963. llist_for_each_entry_safe(obj, on, freed, freed) {
  3964. struct i915_vma *vma, *vn;
  3965. trace_i915_gem_object_destroy(obj);
  3966. mutex_lock(&i915->drm.struct_mutex);
  3967. GEM_BUG_ON(i915_gem_object_is_active(obj));
  3968. list_for_each_entry_safe(vma, vn,
  3969. &obj->vma_list, obj_link) {
  3970. GEM_BUG_ON(i915_vma_is_active(vma));
  3971. vma->flags &= ~I915_VMA_PIN_MASK;
  3972. i915_vma_close(vma);
  3973. }
  3974. GEM_BUG_ON(!list_empty(&obj->vma_list));
  3975. GEM_BUG_ON(!RB_EMPTY_ROOT(&obj->vma_tree));
  3976. /* This serializes freeing with the shrinker. Since the free
  3977. * is delayed, first by RCU then by the workqueue, we want the
  3978. * shrinker to be able to free pages of unreferenced objects,
  3979. * or else we may oom whilst there are plenty of deferred
  3980. * freed objects.
  3981. */
  3982. if (i915_gem_object_has_pages(obj)) {
  3983. spin_lock(&i915->mm.obj_lock);
  3984. list_del_init(&obj->mm.link);
  3985. spin_unlock(&i915->mm.obj_lock);
  3986. }
  3987. mutex_unlock(&i915->drm.struct_mutex);
  3988. GEM_BUG_ON(obj->bind_count);
  3989. GEM_BUG_ON(obj->userfault_count);
  3990. GEM_BUG_ON(atomic_read(&obj->frontbuffer_bits));
  3991. GEM_BUG_ON(!list_empty(&obj->lut_list));
  3992. if (obj->ops->release)
  3993. obj->ops->release(obj);
  3994. if (WARN_ON(i915_gem_object_has_pinned_pages(obj)))
  3995. atomic_set(&obj->mm.pages_pin_count, 0);
  3996. __i915_gem_object_put_pages(obj, I915_MM_NORMAL);
  3997. GEM_BUG_ON(i915_gem_object_has_pages(obj));
  3998. if (obj->base.import_attach)
  3999. drm_prime_gem_destroy(&obj->base, NULL);
  4000. reservation_object_fini(&obj->__builtin_resv);
  4001. drm_gem_object_release(&obj->base);
  4002. i915_gem_info_remove_obj(i915, obj->base.size);
  4003. kfree(obj->bit_17);
  4004. i915_gem_object_free(obj);
  4005. GEM_BUG_ON(!atomic_read(&i915->mm.free_count));
  4006. atomic_dec(&i915->mm.free_count);
  4007. if (on)
  4008. cond_resched();
  4009. }
  4010. intel_runtime_pm_put(i915);
  4011. }
  4012. static void i915_gem_flush_free_objects(struct drm_i915_private *i915)
  4013. {
  4014. struct llist_node *freed;
  4015. /* Free the oldest, most stale object to keep the free_list short */
  4016. freed = NULL;
  4017. if (!llist_empty(&i915->mm.free_list)) { /* quick test for hotpath */
  4018. /* Only one consumer of llist_del_first() allowed */
  4019. spin_lock(&i915->mm.free_lock);
  4020. freed = llist_del_first(&i915->mm.free_list);
  4021. spin_unlock(&i915->mm.free_lock);
  4022. }
  4023. if (unlikely(freed)) {
  4024. freed->next = NULL;
  4025. __i915_gem_free_objects(i915, freed);
  4026. }
  4027. }
  4028. static void __i915_gem_free_work(struct work_struct *work)
  4029. {
  4030. struct drm_i915_private *i915 =
  4031. container_of(work, struct drm_i915_private, mm.free_work);
  4032. struct llist_node *freed;
  4033. /*
  4034. * All file-owned VMA should have been released by this point through
  4035. * i915_gem_close_object(), or earlier by i915_gem_context_close().
  4036. * However, the object may also be bound into the global GTT (e.g.
  4037. * older GPUs without per-process support, or for direct access through
  4038. * the GTT either for the user or for scanout). Those VMA still need to
  4039. * unbound now.
  4040. */
  4041. spin_lock(&i915->mm.free_lock);
  4042. while ((freed = llist_del_all(&i915->mm.free_list))) {
  4043. spin_unlock(&i915->mm.free_lock);
  4044. __i915_gem_free_objects(i915, freed);
  4045. if (need_resched())
  4046. return;
  4047. spin_lock(&i915->mm.free_lock);
  4048. }
  4049. spin_unlock(&i915->mm.free_lock);
  4050. }
  4051. static void __i915_gem_free_object_rcu(struct rcu_head *head)
  4052. {
  4053. struct drm_i915_gem_object *obj =
  4054. container_of(head, typeof(*obj), rcu);
  4055. struct drm_i915_private *i915 = to_i915(obj->base.dev);
  4056. /*
  4057. * Since we require blocking on struct_mutex to unbind the freed
  4058. * object from the GPU before releasing resources back to the
  4059. * system, we can not do that directly from the RCU callback (which may
  4060. * be a softirq context), but must instead then defer that work onto a
  4061. * kthread. We use the RCU callback rather than move the freed object
  4062. * directly onto the work queue so that we can mix between using the
  4063. * worker and performing frees directly from subsequent allocations for
  4064. * crude but effective memory throttling.
  4065. */
  4066. if (llist_add(&obj->freed, &i915->mm.free_list))
  4067. queue_work(i915->wq, &i915->mm.free_work);
  4068. }
  4069. void i915_gem_free_object(struct drm_gem_object *gem_obj)
  4070. {
  4071. struct drm_i915_gem_object *obj = to_intel_bo(gem_obj);
  4072. if (obj->mm.quirked)
  4073. __i915_gem_object_unpin_pages(obj);
  4074. if (discard_backing_storage(obj))
  4075. obj->mm.madv = I915_MADV_DONTNEED;
  4076. /*
  4077. * Before we free the object, make sure any pure RCU-only
  4078. * read-side critical sections are complete, e.g.
  4079. * i915_gem_busy_ioctl(). For the corresponding synchronized
  4080. * lookup see i915_gem_object_lookup_rcu().
  4081. */
  4082. atomic_inc(&to_i915(obj->base.dev)->mm.free_count);
  4083. call_rcu(&obj->rcu, __i915_gem_free_object_rcu);
  4084. }
  4085. void __i915_gem_object_release_unless_active(struct drm_i915_gem_object *obj)
  4086. {
  4087. lockdep_assert_held(&obj->base.dev->struct_mutex);
  4088. if (!i915_gem_object_has_active_reference(obj) &&
  4089. i915_gem_object_is_active(obj))
  4090. i915_gem_object_set_active_reference(obj);
  4091. else
  4092. i915_gem_object_put(obj);
  4093. }
  4094. static void assert_kernel_context_is_current(struct drm_i915_private *i915)
  4095. {
  4096. struct i915_gem_context *kernel_context = i915->kernel_context;
  4097. struct intel_engine_cs *engine;
  4098. enum intel_engine_id id;
  4099. for_each_engine(engine, i915, id) {
  4100. GEM_BUG_ON(__i915_gem_active_peek(&engine->timeline->last_request));
  4101. GEM_BUG_ON(engine->last_retired_context != kernel_context);
  4102. }
  4103. }
  4104. void i915_gem_sanitize(struct drm_i915_private *i915)
  4105. {
  4106. if (i915_terminally_wedged(&i915->gpu_error)) {
  4107. mutex_lock(&i915->drm.struct_mutex);
  4108. i915_gem_unset_wedged(i915);
  4109. mutex_unlock(&i915->drm.struct_mutex);
  4110. }
  4111. /*
  4112. * If we inherit context state from the BIOS or earlier occupants
  4113. * of the GPU, the GPU may be in an inconsistent state when we
  4114. * try to take over. The only way to remove the earlier state
  4115. * is by resetting. However, resetting on earlier gen is tricky as
  4116. * it may impact the display and we are uncertain about the stability
  4117. * of the reset, so this could be applied to even earlier gen.
  4118. */
  4119. if (INTEL_GEN(i915) >= 5 && intel_has_gpu_reset(i915))
  4120. WARN_ON(intel_gpu_reset(i915, ALL_ENGINES));
  4121. }
  4122. int i915_gem_suspend(struct drm_i915_private *dev_priv)
  4123. {
  4124. struct drm_device *dev = &dev_priv->drm;
  4125. int ret;
  4126. intel_runtime_pm_get(dev_priv);
  4127. intel_suspend_gt_powersave(dev_priv);
  4128. mutex_lock(&dev->struct_mutex);
  4129. /* We have to flush all the executing contexts to main memory so
  4130. * that they can saved in the hibernation image. To ensure the last
  4131. * context image is coherent, we have to switch away from it. That
  4132. * leaves the dev_priv->kernel_context still active when
  4133. * we actually suspend, and its image in memory may not match the GPU
  4134. * state. Fortunately, the kernel_context is disposable and we do
  4135. * not rely on its state.
  4136. */
  4137. if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
  4138. ret = i915_gem_switch_to_kernel_context(dev_priv);
  4139. if (ret)
  4140. goto err_unlock;
  4141. ret = i915_gem_wait_for_idle(dev_priv,
  4142. I915_WAIT_INTERRUPTIBLE |
  4143. I915_WAIT_LOCKED);
  4144. if (ret && ret != -EIO)
  4145. goto err_unlock;
  4146. assert_kernel_context_is_current(dev_priv);
  4147. }
  4148. i915_gem_contexts_lost(dev_priv);
  4149. mutex_unlock(&dev->struct_mutex);
  4150. intel_uc_suspend(dev_priv);
  4151. cancel_delayed_work_sync(&dev_priv->gpu_error.hangcheck_work);
  4152. cancel_delayed_work_sync(&dev_priv->gt.retire_work);
  4153. /* As the idle_work is rearming if it detects a race, play safe and
  4154. * repeat the flush until it is definitely idle.
  4155. */
  4156. drain_delayed_work(&dev_priv->gt.idle_work);
  4157. /* Assert that we sucessfully flushed all the work and
  4158. * reset the GPU back to its idle, low power state.
  4159. */
  4160. WARN_ON(dev_priv->gt.awake);
  4161. if (WARN_ON(!intel_engines_are_idle(dev_priv)))
  4162. i915_gem_set_wedged(dev_priv); /* no hope, discard everything */
  4163. /*
  4164. * Neither the BIOS, ourselves or any other kernel
  4165. * expects the system to be in execlists mode on startup,
  4166. * so we need to reset the GPU back to legacy mode. And the only
  4167. * known way to disable logical contexts is through a GPU reset.
  4168. *
  4169. * So in order to leave the system in a known default configuration,
  4170. * always reset the GPU upon unload and suspend. Afterwards we then
  4171. * clean up the GEM state tracking, flushing off the requests and
  4172. * leaving the system in a known idle state.
  4173. *
  4174. * Note that is of the upmost importance that the GPU is idle and
  4175. * all stray writes are flushed *before* we dismantle the backing
  4176. * storage for the pinned objects.
  4177. *
  4178. * However, since we are uncertain that resetting the GPU on older
  4179. * machines is a good idea, we don't - just in case it leaves the
  4180. * machine in an unusable condition.
  4181. */
  4182. i915_gem_sanitize(dev_priv);
  4183. intel_runtime_pm_put(dev_priv);
  4184. return 0;
  4185. err_unlock:
  4186. mutex_unlock(&dev->struct_mutex);
  4187. intel_runtime_pm_put(dev_priv);
  4188. return ret;
  4189. }
  4190. void i915_gem_resume(struct drm_i915_private *i915)
  4191. {
  4192. WARN_ON(i915->gt.awake);
  4193. mutex_lock(&i915->drm.struct_mutex);
  4194. intel_uncore_forcewake_get(i915, FORCEWAKE_ALL);
  4195. i915_gem_restore_gtt_mappings(i915);
  4196. i915_gem_restore_fences(i915);
  4197. /*
  4198. * As we didn't flush the kernel context before suspend, we cannot
  4199. * guarantee that the context image is complete. So let's just reset
  4200. * it and start again.
  4201. */
  4202. i915->gt.resume(i915);
  4203. if (i915_gem_init_hw(i915))
  4204. goto err_wedged;
  4205. intel_uc_resume(i915);
  4206. /* Always reload a context for powersaving. */
  4207. if (i915_gem_switch_to_kernel_context(i915))
  4208. goto err_wedged;
  4209. out_unlock:
  4210. intel_uncore_forcewake_put(i915, FORCEWAKE_ALL);
  4211. mutex_unlock(&i915->drm.struct_mutex);
  4212. return;
  4213. err_wedged:
  4214. if (!i915_terminally_wedged(&i915->gpu_error)) {
  4215. DRM_ERROR("failed to re-initialize GPU, declaring wedged!\n");
  4216. i915_gem_set_wedged(i915);
  4217. }
  4218. goto out_unlock;
  4219. }
  4220. void i915_gem_init_swizzling(struct drm_i915_private *dev_priv)
  4221. {
  4222. if (INTEL_GEN(dev_priv) < 5 ||
  4223. dev_priv->mm.bit_6_swizzle_x == I915_BIT_6_SWIZZLE_NONE)
  4224. return;
  4225. I915_WRITE(DISP_ARB_CTL, I915_READ(DISP_ARB_CTL) |
  4226. DISP_TILE_SURFACE_SWIZZLING);
  4227. if (IS_GEN5(dev_priv))
  4228. return;
  4229. I915_WRITE(TILECTL, I915_READ(TILECTL) | TILECTL_SWZCTL);
  4230. if (IS_GEN6(dev_priv))
  4231. I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_SNB));
  4232. else if (IS_GEN7(dev_priv))
  4233. I915_WRITE(ARB_MODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_IVB));
  4234. else if (IS_GEN8(dev_priv))
  4235. I915_WRITE(GAMTARBMODE, _MASKED_BIT_ENABLE(ARB_MODE_SWIZZLE_BDW));
  4236. else
  4237. BUG();
  4238. }
  4239. static void init_unused_ring(struct drm_i915_private *dev_priv, u32 base)
  4240. {
  4241. I915_WRITE(RING_CTL(base), 0);
  4242. I915_WRITE(RING_HEAD(base), 0);
  4243. I915_WRITE(RING_TAIL(base), 0);
  4244. I915_WRITE(RING_START(base), 0);
  4245. }
  4246. static void init_unused_rings(struct drm_i915_private *dev_priv)
  4247. {
  4248. if (IS_I830(dev_priv)) {
  4249. init_unused_ring(dev_priv, PRB1_BASE);
  4250. init_unused_ring(dev_priv, SRB0_BASE);
  4251. init_unused_ring(dev_priv, SRB1_BASE);
  4252. init_unused_ring(dev_priv, SRB2_BASE);
  4253. init_unused_ring(dev_priv, SRB3_BASE);
  4254. } else if (IS_GEN2(dev_priv)) {
  4255. init_unused_ring(dev_priv, SRB0_BASE);
  4256. init_unused_ring(dev_priv, SRB1_BASE);
  4257. } else if (IS_GEN3(dev_priv)) {
  4258. init_unused_ring(dev_priv, PRB1_BASE);
  4259. init_unused_ring(dev_priv, PRB2_BASE);
  4260. }
  4261. }
  4262. static int __i915_gem_restart_engines(void *data)
  4263. {
  4264. struct drm_i915_private *i915 = data;
  4265. struct intel_engine_cs *engine;
  4266. enum intel_engine_id id;
  4267. int err;
  4268. for_each_engine(engine, i915, id) {
  4269. err = engine->init_hw(engine);
  4270. if (err) {
  4271. DRM_ERROR("Failed to restart %s (%d)\n",
  4272. engine->name, err);
  4273. return err;
  4274. }
  4275. }
  4276. return 0;
  4277. }
  4278. int i915_gem_init_hw(struct drm_i915_private *dev_priv)
  4279. {
  4280. int ret;
  4281. dev_priv->gt.last_init_time = ktime_get();
  4282. /* Double layer security blanket, see i915_gem_init() */
  4283. intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
  4284. if (HAS_EDRAM(dev_priv) && INTEL_GEN(dev_priv) < 9)
  4285. I915_WRITE(HSW_IDICR, I915_READ(HSW_IDICR) | IDIHASHMSK(0xf));
  4286. if (IS_HASWELL(dev_priv))
  4287. I915_WRITE(MI_PREDICATE_RESULT_2, IS_HSW_GT3(dev_priv) ?
  4288. LOWER_SLICE_ENABLED : LOWER_SLICE_DISABLED);
  4289. if (HAS_PCH_NOP(dev_priv)) {
  4290. if (IS_IVYBRIDGE(dev_priv)) {
  4291. u32 temp = I915_READ(GEN7_MSG_CTL);
  4292. temp &= ~(WAIT_FOR_PCH_FLR_ACK | WAIT_FOR_PCH_RESET_ACK);
  4293. I915_WRITE(GEN7_MSG_CTL, temp);
  4294. } else if (INTEL_GEN(dev_priv) >= 7) {
  4295. u32 temp = I915_READ(HSW_NDE_RSTWRN_OPT);
  4296. temp &= ~RESET_PCH_HANDSHAKE_ENABLE;
  4297. I915_WRITE(HSW_NDE_RSTWRN_OPT, temp);
  4298. }
  4299. }
  4300. i915_gem_init_swizzling(dev_priv);
  4301. /*
  4302. * At least 830 can leave some of the unused rings
  4303. * "active" (ie. head != tail) after resume which
  4304. * will prevent c3 entry. Makes sure all unused rings
  4305. * are totally idle.
  4306. */
  4307. init_unused_rings(dev_priv);
  4308. BUG_ON(!dev_priv->kernel_context);
  4309. if (i915_terminally_wedged(&dev_priv->gpu_error)) {
  4310. ret = -EIO;
  4311. goto out;
  4312. }
  4313. ret = i915_ppgtt_init_hw(dev_priv);
  4314. if (ret) {
  4315. DRM_ERROR("Enabling PPGTT failed (%d)\n", ret);
  4316. goto out;
  4317. }
  4318. /* We can't enable contexts until all firmware is loaded */
  4319. ret = intel_uc_init_hw(dev_priv);
  4320. if (ret) {
  4321. DRM_ERROR("Enabling uc failed (%d)\n", ret);
  4322. goto out;
  4323. }
  4324. intel_mocs_init_l3cc_table(dev_priv);
  4325. /* Only when the HW is re-initialised, can we replay the requests */
  4326. ret = __i915_gem_restart_engines(dev_priv);
  4327. out:
  4328. intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
  4329. return ret;
  4330. }
  4331. static int __intel_engines_record_defaults(struct drm_i915_private *i915)
  4332. {
  4333. struct i915_gem_context *ctx;
  4334. struct intel_engine_cs *engine;
  4335. enum intel_engine_id id;
  4336. int err;
  4337. /*
  4338. * As we reset the gpu during very early sanitisation, the current
  4339. * register state on the GPU should reflect its defaults values.
  4340. * We load a context onto the hw (with restore-inhibit), then switch
  4341. * over to a second context to save that default register state. We
  4342. * can then prime every new context with that state so they all start
  4343. * from the same default HW values.
  4344. */
  4345. ctx = i915_gem_context_create_kernel(i915, 0);
  4346. if (IS_ERR(ctx))
  4347. return PTR_ERR(ctx);
  4348. for_each_engine(engine, i915, id) {
  4349. struct i915_request *rq;
  4350. rq = i915_request_alloc(engine, ctx);
  4351. if (IS_ERR(rq)) {
  4352. err = PTR_ERR(rq);
  4353. goto out_ctx;
  4354. }
  4355. err = 0;
  4356. if (engine->init_context)
  4357. err = engine->init_context(rq);
  4358. __i915_request_add(rq, true);
  4359. if (err)
  4360. goto err_active;
  4361. }
  4362. err = i915_gem_switch_to_kernel_context(i915);
  4363. if (err)
  4364. goto err_active;
  4365. err = i915_gem_wait_for_idle(i915, I915_WAIT_LOCKED);
  4366. if (err)
  4367. goto err_active;
  4368. assert_kernel_context_is_current(i915);
  4369. for_each_engine(engine, i915, id) {
  4370. struct i915_vma *state;
  4371. state = ctx->engine[id].state;
  4372. if (!state)
  4373. continue;
  4374. /*
  4375. * As we will hold a reference to the logical state, it will
  4376. * not be torn down with the context, and importantly the
  4377. * object will hold onto its vma (making it possible for a
  4378. * stray GTT write to corrupt our defaults). Unmap the vma
  4379. * from the GTT to prevent such accidents and reclaim the
  4380. * space.
  4381. */
  4382. err = i915_vma_unbind(state);
  4383. if (err)
  4384. goto err_active;
  4385. err = i915_gem_object_set_to_cpu_domain(state->obj, false);
  4386. if (err)
  4387. goto err_active;
  4388. engine->default_state = i915_gem_object_get(state->obj);
  4389. }
  4390. if (IS_ENABLED(CONFIG_DRM_I915_DEBUG_GEM)) {
  4391. unsigned int found = intel_engines_has_context_isolation(i915);
  4392. /*
  4393. * Make sure that classes with multiple engine instances all
  4394. * share the same basic configuration.
  4395. */
  4396. for_each_engine(engine, i915, id) {
  4397. unsigned int bit = BIT(engine->uabi_class);
  4398. unsigned int expected = engine->default_state ? bit : 0;
  4399. if ((found & bit) != expected) {
  4400. DRM_ERROR("mismatching default context state for class %d on engine %s\n",
  4401. engine->uabi_class, engine->name);
  4402. }
  4403. }
  4404. }
  4405. out_ctx:
  4406. i915_gem_context_set_closed(ctx);
  4407. i915_gem_context_put(ctx);
  4408. return err;
  4409. err_active:
  4410. /*
  4411. * If we have to abandon now, we expect the engines to be idle
  4412. * and ready to be torn-down. First try to flush any remaining
  4413. * request, ensure we are pointing at the kernel context and
  4414. * then remove it.
  4415. */
  4416. if (WARN_ON(i915_gem_switch_to_kernel_context(i915)))
  4417. goto out_ctx;
  4418. if (WARN_ON(i915_gem_wait_for_idle(i915, I915_WAIT_LOCKED)))
  4419. goto out_ctx;
  4420. i915_gem_contexts_lost(i915);
  4421. goto out_ctx;
  4422. }
  4423. int i915_gem_init(struct drm_i915_private *dev_priv)
  4424. {
  4425. int ret;
  4426. /*
  4427. * We need to fallback to 4K pages since gvt gtt handling doesn't
  4428. * support huge page entries - we will need to check either hypervisor
  4429. * mm can support huge guest page or just do emulation in gvt.
  4430. */
  4431. if (intel_vgpu_active(dev_priv))
  4432. mkwrite_device_info(dev_priv)->page_sizes =
  4433. I915_GTT_PAGE_SIZE_4K;
  4434. dev_priv->mm.unordered_timeline = dma_fence_context_alloc(1);
  4435. if (HAS_LOGICAL_RING_CONTEXTS(dev_priv)) {
  4436. dev_priv->gt.resume = intel_lr_context_resume;
  4437. dev_priv->gt.cleanup_engine = intel_logical_ring_cleanup;
  4438. } else {
  4439. dev_priv->gt.resume = intel_legacy_submission_resume;
  4440. dev_priv->gt.cleanup_engine = intel_engine_cleanup;
  4441. }
  4442. ret = i915_gem_init_userptr(dev_priv);
  4443. if (ret)
  4444. return ret;
  4445. ret = intel_uc_init_misc(dev_priv);
  4446. if (ret)
  4447. return ret;
  4448. /* This is just a security blanket to placate dragons.
  4449. * On some systems, we very sporadically observe that the first TLBs
  4450. * used by the CS may be stale, despite us poking the TLB reset. If
  4451. * we hold the forcewake during initialisation these problems
  4452. * just magically go away.
  4453. */
  4454. mutex_lock(&dev_priv->drm.struct_mutex);
  4455. intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
  4456. ret = i915_gem_init_ggtt(dev_priv);
  4457. if (ret) {
  4458. GEM_BUG_ON(ret == -EIO);
  4459. goto err_unlock;
  4460. }
  4461. ret = i915_gem_contexts_init(dev_priv);
  4462. if (ret) {
  4463. GEM_BUG_ON(ret == -EIO);
  4464. goto err_ggtt;
  4465. }
  4466. ret = intel_engines_init(dev_priv);
  4467. if (ret) {
  4468. GEM_BUG_ON(ret == -EIO);
  4469. goto err_context;
  4470. }
  4471. intel_init_gt_powersave(dev_priv);
  4472. ret = intel_uc_init(dev_priv);
  4473. if (ret)
  4474. goto err_pm;
  4475. ret = i915_gem_init_hw(dev_priv);
  4476. if (ret)
  4477. goto err_uc_init;
  4478. /*
  4479. * Despite its name intel_init_clock_gating applies both display
  4480. * clock gating workarounds; GT mmio workarounds and the occasional
  4481. * GT power context workaround. Worse, sometimes it includes a context
  4482. * register workaround which we need to apply before we record the
  4483. * default HW state for all contexts.
  4484. *
  4485. * FIXME: break up the workarounds and apply them at the right time!
  4486. */
  4487. intel_init_clock_gating(dev_priv);
  4488. ret = __intel_engines_record_defaults(dev_priv);
  4489. if (ret)
  4490. goto err_init_hw;
  4491. if (i915_inject_load_failure()) {
  4492. ret = -ENODEV;
  4493. goto err_init_hw;
  4494. }
  4495. if (i915_inject_load_failure()) {
  4496. ret = -EIO;
  4497. goto err_init_hw;
  4498. }
  4499. intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
  4500. mutex_unlock(&dev_priv->drm.struct_mutex);
  4501. return 0;
  4502. /*
  4503. * Unwinding is complicated by that we want to handle -EIO to mean
  4504. * disable GPU submission but keep KMS alive. We want to mark the
  4505. * HW as irrevisibly wedged, but keep enough state around that the
  4506. * driver doesn't explode during runtime.
  4507. */
  4508. err_init_hw:
  4509. i915_gem_wait_for_idle(dev_priv, I915_WAIT_LOCKED);
  4510. i915_gem_contexts_lost(dev_priv);
  4511. intel_uc_fini_hw(dev_priv);
  4512. err_uc_init:
  4513. intel_uc_fini(dev_priv);
  4514. err_pm:
  4515. if (ret != -EIO) {
  4516. intel_cleanup_gt_powersave(dev_priv);
  4517. i915_gem_cleanup_engines(dev_priv);
  4518. }
  4519. err_context:
  4520. if (ret != -EIO)
  4521. i915_gem_contexts_fini(dev_priv);
  4522. err_ggtt:
  4523. err_unlock:
  4524. intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
  4525. mutex_unlock(&dev_priv->drm.struct_mutex);
  4526. intel_uc_fini_misc(dev_priv);
  4527. if (ret != -EIO)
  4528. i915_gem_cleanup_userptr(dev_priv);
  4529. if (ret == -EIO) {
  4530. /*
  4531. * Allow engine initialisation to fail by marking the GPU as
  4532. * wedged. But we only want to do this where the GPU is angry,
  4533. * for all other failure, such as an allocation failure, bail.
  4534. */
  4535. if (!i915_terminally_wedged(&dev_priv->gpu_error)) {
  4536. DRM_ERROR("Failed to initialize GPU, declaring it wedged\n");
  4537. i915_gem_set_wedged(dev_priv);
  4538. }
  4539. ret = 0;
  4540. }
  4541. i915_gem_drain_freed_objects(dev_priv);
  4542. return ret;
  4543. }
  4544. void i915_gem_init_mmio(struct drm_i915_private *i915)
  4545. {
  4546. i915_gem_sanitize(i915);
  4547. }
  4548. void
  4549. i915_gem_cleanup_engines(struct drm_i915_private *dev_priv)
  4550. {
  4551. struct intel_engine_cs *engine;
  4552. enum intel_engine_id id;
  4553. for_each_engine(engine, dev_priv, id)
  4554. dev_priv->gt.cleanup_engine(engine);
  4555. }
  4556. void
  4557. i915_gem_load_init_fences(struct drm_i915_private *dev_priv)
  4558. {
  4559. int i;
  4560. if (INTEL_GEN(dev_priv) >= 7 && !IS_VALLEYVIEW(dev_priv) &&
  4561. !IS_CHERRYVIEW(dev_priv))
  4562. dev_priv->num_fence_regs = 32;
  4563. else if (INTEL_GEN(dev_priv) >= 4 ||
  4564. IS_I945G(dev_priv) || IS_I945GM(dev_priv) ||
  4565. IS_G33(dev_priv) || IS_PINEVIEW(dev_priv))
  4566. dev_priv->num_fence_regs = 16;
  4567. else
  4568. dev_priv->num_fence_regs = 8;
  4569. if (intel_vgpu_active(dev_priv))
  4570. dev_priv->num_fence_regs =
  4571. I915_READ(vgtif_reg(avail_rs.fence_num));
  4572. /* Initialize fence registers to zero */
  4573. for (i = 0; i < dev_priv->num_fence_regs; i++) {
  4574. struct drm_i915_fence_reg *fence = &dev_priv->fence_regs[i];
  4575. fence->i915 = dev_priv;
  4576. fence->id = i;
  4577. list_add_tail(&fence->link, &dev_priv->mm.fence_list);
  4578. }
  4579. i915_gem_restore_fences(dev_priv);
  4580. i915_gem_detect_bit_6_swizzle(dev_priv);
  4581. }
  4582. static void i915_gem_init__mm(struct drm_i915_private *i915)
  4583. {
  4584. spin_lock_init(&i915->mm.object_stat_lock);
  4585. spin_lock_init(&i915->mm.obj_lock);
  4586. spin_lock_init(&i915->mm.free_lock);
  4587. init_llist_head(&i915->mm.free_list);
  4588. INIT_LIST_HEAD(&i915->mm.unbound_list);
  4589. INIT_LIST_HEAD(&i915->mm.bound_list);
  4590. INIT_LIST_HEAD(&i915->mm.fence_list);
  4591. INIT_LIST_HEAD(&i915->mm.userfault_list);
  4592. INIT_WORK(&i915->mm.free_work, __i915_gem_free_work);
  4593. }
  4594. int
  4595. i915_gem_load_init(struct drm_i915_private *dev_priv)
  4596. {
  4597. int err = -ENOMEM;
  4598. dev_priv->objects = KMEM_CACHE(drm_i915_gem_object, SLAB_HWCACHE_ALIGN);
  4599. if (!dev_priv->objects)
  4600. goto err_out;
  4601. dev_priv->vmas = KMEM_CACHE(i915_vma, SLAB_HWCACHE_ALIGN);
  4602. if (!dev_priv->vmas)
  4603. goto err_objects;
  4604. dev_priv->luts = KMEM_CACHE(i915_lut_handle, 0);
  4605. if (!dev_priv->luts)
  4606. goto err_vmas;
  4607. dev_priv->requests = KMEM_CACHE(i915_request,
  4608. SLAB_HWCACHE_ALIGN |
  4609. SLAB_RECLAIM_ACCOUNT |
  4610. SLAB_TYPESAFE_BY_RCU);
  4611. if (!dev_priv->requests)
  4612. goto err_luts;
  4613. dev_priv->dependencies = KMEM_CACHE(i915_dependency,
  4614. SLAB_HWCACHE_ALIGN |
  4615. SLAB_RECLAIM_ACCOUNT);
  4616. if (!dev_priv->dependencies)
  4617. goto err_requests;
  4618. dev_priv->priorities = KMEM_CACHE(i915_priolist, SLAB_HWCACHE_ALIGN);
  4619. if (!dev_priv->priorities)
  4620. goto err_dependencies;
  4621. mutex_lock(&dev_priv->drm.struct_mutex);
  4622. INIT_LIST_HEAD(&dev_priv->gt.timelines);
  4623. err = i915_gem_timeline_init__global(dev_priv);
  4624. mutex_unlock(&dev_priv->drm.struct_mutex);
  4625. if (err)
  4626. goto err_priorities;
  4627. i915_gem_init__mm(dev_priv);
  4628. INIT_DELAYED_WORK(&dev_priv->gt.retire_work,
  4629. i915_gem_retire_work_handler);
  4630. INIT_DELAYED_WORK(&dev_priv->gt.idle_work,
  4631. i915_gem_idle_work_handler);
  4632. init_waitqueue_head(&dev_priv->gpu_error.wait_queue);
  4633. init_waitqueue_head(&dev_priv->gpu_error.reset_queue);
  4634. atomic_set(&dev_priv->mm.bsd_engine_dispatch_index, 0);
  4635. spin_lock_init(&dev_priv->fb_tracking.lock);
  4636. err = i915_gemfs_init(dev_priv);
  4637. if (err)
  4638. DRM_NOTE("Unable to create a private tmpfs mount, hugepage support will be disabled(%d).\n", err);
  4639. return 0;
  4640. err_priorities:
  4641. kmem_cache_destroy(dev_priv->priorities);
  4642. err_dependencies:
  4643. kmem_cache_destroy(dev_priv->dependencies);
  4644. err_requests:
  4645. kmem_cache_destroy(dev_priv->requests);
  4646. err_luts:
  4647. kmem_cache_destroy(dev_priv->luts);
  4648. err_vmas:
  4649. kmem_cache_destroy(dev_priv->vmas);
  4650. err_objects:
  4651. kmem_cache_destroy(dev_priv->objects);
  4652. err_out:
  4653. return err;
  4654. }
  4655. void i915_gem_load_cleanup(struct drm_i915_private *dev_priv)
  4656. {
  4657. i915_gem_drain_freed_objects(dev_priv);
  4658. GEM_BUG_ON(!llist_empty(&dev_priv->mm.free_list));
  4659. GEM_BUG_ON(atomic_read(&dev_priv->mm.free_count));
  4660. WARN_ON(dev_priv->mm.object_count);
  4661. mutex_lock(&dev_priv->drm.struct_mutex);
  4662. i915_gem_timeline_fini(&dev_priv->gt.global_timeline);
  4663. WARN_ON(!list_empty(&dev_priv->gt.timelines));
  4664. mutex_unlock(&dev_priv->drm.struct_mutex);
  4665. kmem_cache_destroy(dev_priv->priorities);
  4666. kmem_cache_destroy(dev_priv->dependencies);
  4667. kmem_cache_destroy(dev_priv->requests);
  4668. kmem_cache_destroy(dev_priv->luts);
  4669. kmem_cache_destroy(dev_priv->vmas);
  4670. kmem_cache_destroy(dev_priv->objects);
  4671. /* And ensure that our DESTROY_BY_RCU slabs are truly destroyed */
  4672. rcu_barrier();
  4673. i915_gemfs_fini(dev_priv);
  4674. }
  4675. int i915_gem_freeze(struct drm_i915_private *dev_priv)
  4676. {
  4677. /* Discard all purgeable objects, let userspace recover those as
  4678. * required after resuming.
  4679. */
  4680. i915_gem_shrink_all(dev_priv);
  4681. return 0;
  4682. }
  4683. int i915_gem_freeze_late(struct drm_i915_private *dev_priv)
  4684. {
  4685. struct drm_i915_gem_object *obj;
  4686. struct list_head *phases[] = {
  4687. &dev_priv->mm.unbound_list,
  4688. &dev_priv->mm.bound_list,
  4689. NULL
  4690. }, **p;
  4691. /* Called just before we write the hibernation image.
  4692. *
  4693. * We need to update the domain tracking to reflect that the CPU
  4694. * will be accessing all the pages to create and restore from the
  4695. * hibernation, and so upon restoration those pages will be in the
  4696. * CPU domain.
  4697. *
  4698. * To make sure the hibernation image contains the latest state,
  4699. * we update that state just before writing out the image.
  4700. *
  4701. * To try and reduce the hibernation image, we manually shrink
  4702. * the objects as well, see i915_gem_freeze()
  4703. */
  4704. i915_gem_shrink(dev_priv, -1UL, NULL, I915_SHRINK_UNBOUND);
  4705. i915_gem_drain_freed_objects(dev_priv);
  4706. spin_lock(&dev_priv->mm.obj_lock);
  4707. for (p = phases; *p; p++) {
  4708. list_for_each_entry(obj, *p, mm.link)
  4709. __start_cpu_write(obj);
  4710. }
  4711. spin_unlock(&dev_priv->mm.obj_lock);
  4712. return 0;
  4713. }
  4714. void i915_gem_release(struct drm_device *dev, struct drm_file *file)
  4715. {
  4716. struct drm_i915_file_private *file_priv = file->driver_priv;
  4717. struct i915_request *request;
  4718. /* Clean up our request list when the client is going away, so that
  4719. * later retire_requests won't dereference our soon-to-be-gone
  4720. * file_priv.
  4721. */
  4722. spin_lock(&file_priv->mm.lock);
  4723. list_for_each_entry(request, &file_priv->mm.request_list, client_link)
  4724. request->file_priv = NULL;
  4725. spin_unlock(&file_priv->mm.lock);
  4726. }
  4727. int i915_gem_open(struct drm_i915_private *i915, struct drm_file *file)
  4728. {
  4729. struct drm_i915_file_private *file_priv;
  4730. int ret;
  4731. DRM_DEBUG("\n");
  4732. file_priv = kzalloc(sizeof(*file_priv), GFP_KERNEL);
  4733. if (!file_priv)
  4734. return -ENOMEM;
  4735. file->driver_priv = file_priv;
  4736. file_priv->dev_priv = i915;
  4737. file_priv->file = file;
  4738. spin_lock_init(&file_priv->mm.lock);
  4739. INIT_LIST_HEAD(&file_priv->mm.request_list);
  4740. file_priv->bsd_engine = -1;
  4741. ret = i915_gem_context_open(i915, file);
  4742. if (ret)
  4743. kfree(file_priv);
  4744. return ret;
  4745. }
  4746. /**
  4747. * i915_gem_track_fb - update frontbuffer tracking
  4748. * @old: current GEM buffer for the frontbuffer slots
  4749. * @new: new GEM buffer for the frontbuffer slots
  4750. * @frontbuffer_bits: bitmask of frontbuffer slots
  4751. *
  4752. * This updates the frontbuffer tracking bits @frontbuffer_bits by clearing them
  4753. * from @old and setting them in @new. Both @old and @new can be NULL.
  4754. */
  4755. void i915_gem_track_fb(struct drm_i915_gem_object *old,
  4756. struct drm_i915_gem_object *new,
  4757. unsigned frontbuffer_bits)
  4758. {
  4759. /* Control of individual bits within the mask are guarded by
  4760. * the owning plane->mutex, i.e. we can never see concurrent
  4761. * manipulation of individual bits. But since the bitfield as a whole
  4762. * is updated using RMW, we need to use atomics in order to update
  4763. * the bits.
  4764. */
  4765. BUILD_BUG_ON(INTEL_FRONTBUFFER_BITS_PER_PIPE * I915_MAX_PIPES >
  4766. sizeof(atomic_t) * BITS_PER_BYTE);
  4767. if (old) {
  4768. WARN_ON(!(atomic_read(&old->frontbuffer_bits) & frontbuffer_bits));
  4769. atomic_andnot(frontbuffer_bits, &old->frontbuffer_bits);
  4770. }
  4771. if (new) {
  4772. WARN_ON(atomic_read(&new->frontbuffer_bits) & frontbuffer_bits);
  4773. atomic_or(frontbuffer_bits, &new->frontbuffer_bits);
  4774. }
  4775. }
  4776. /* Allocate a new GEM object and fill it with the supplied data */
  4777. struct drm_i915_gem_object *
  4778. i915_gem_object_create_from_data(struct drm_i915_private *dev_priv,
  4779. const void *data, size_t size)
  4780. {
  4781. struct drm_i915_gem_object *obj;
  4782. struct file *file;
  4783. size_t offset;
  4784. int err;
  4785. obj = i915_gem_object_create(dev_priv, round_up(size, PAGE_SIZE));
  4786. if (IS_ERR(obj))
  4787. return obj;
  4788. GEM_BUG_ON(obj->write_domain != I915_GEM_DOMAIN_CPU);
  4789. file = obj->base.filp;
  4790. offset = 0;
  4791. do {
  4792. unsigned int len = min_t(typeof(size), size, PAGE_SIZE);
  4793. struct page *page;
  4794. void *pgdata, *vaddr;
  4795. err = pagecache_write_begin(file, file->f_mapping,
  4796. offset, len, 0,
  4797. &page, &pgdata);
  4798. if (err < 0)
  4799. goto fail;
  4800. vaddr = kmap(page);
  4801. memcpy(vaddr, data, len);
  4802. kunmap(page);
  4803. err = pagecache_write_end(file, file->f_mapping,
  4804. offset, len, len,
  4805. page, pgdata);
  4806. if (err < 0)
  4807. goto fail;
  4808. size -= len;
  4809. data += len;
  4810. offset += len;
  4811. } while (size);
  4812. return obj;
  4813. fail:
  4814. i915_gem_object_put(obj);
  4815. return ERR_PTR(err);
  4816. }
  4817. struct scatterlist *
  4818. i915_gem_object_get_sg(struct drm_i915_gem_object *obj,
  4819. unsigned int n,
  4820. unsigned int *offset)
  4821. {
  4822. struct i915_gem_object_page_iter *iter = &obj->mm.get_page;
  4823. struct scatterlist *sg;
  4824. unsigned int idx, count;
  4825. might_sleep();
  4826. GEM_BUG_ON(n >= obj->base.size >> PAGE_SHIFT);
  4827. GEM_BUG_ON(!i915_gem_object_has_pinned_pages(obj));
  4828. /* As we iterate forward through the sg, we record each entry in a
  4829. * radixtree for quick repeated (backwards) lookups. If we have seen
  4830. * this index previously, we will have an entry for it.
  4831. *
  4832. * Initial lookup is O(N), but this is amortized to O(1) for
  4833. * sequential page access (where each new request is consecutive
  4834. * to the previous one). Repeated lookups are O(lg(obj->base.size)),
  4835. * i.e. O(1) with a large constant!
  4836. */
  4837. if (n < READ_ONCE(iter->sg_idx))
  4838. goto lookup;
  4839. mutex_lock(&iter->lock);
  4840. /* We prefer to reuse the last sg so that repeated lookup of this
  4841. * (or the subsequent) sg are fast - comparing against the last
  4842. * sg is faster than going through the radixtree.
  4843. */
  4844. sg = iter->sg_pos;
  4845. idx = iter->sg_idx;
  4846. count = __sg_page_count(sg);
  4847. while (idx + count <= n) {
  4848. unsigned long exception, i;
  4849. int ret;
  4850. /* If we cannot allocate and insert this entry, or the
  4851. * individual pages from this range, cancel updating the
  4852. * sg_idx so that on this lookup we are forced to linearly
  4853. * scan onwards, but on future lookups we will try the
  4854. * insertion again (in which case we need to be careful of
  4855. * the error return reporting that we have already inserted
  4856. * this index).
  4857. */
  4858. ret = radix_tree_insert(&iter->radix, idx, sg);
  4859. if (ret && ret != -EEXIST)
  4860. goto scan;
  4861. exception =
  4862. RADIX_TREE_EXCEPTIONAL_ENTRY |
  4863. idx << RADIX_TREE_EXCEPTIONAL_SHIFT;
  4864. for (i = 1; i < count; i++) {
  4865. ret = radix_tree_insert(&iter->radix, idx + i,
  4866. (void *)exception);
  4867. if (ret && ret != -EEXIST)
  4868. goto scan;
  4869. }
  4870. idx += count;
  4871. sg = ____sg_next(sg);
  4872. count = __sg_page_count(sg);
  4873. }
  4874. scan:
  4875. iter->sg_pos = sg;
  4876. iter->sg_idx = idx;
  4877. mutex_unlock(&iter->lock);
  4878. if (unlikely(n < idx)) /* insertion completed by another thread */
  4879. goto lookup;
  4880. /* In case we failed to insert the entry into the radixtree, we need
  4881. * to look beyond the current sg.
  4882. */
  4883. while (idx + count <= n) {
  4884. idx += count;
  4885. sg = ____sg_next(sg);
  4886. count = __sg_page_count(sg);
  4887. }
  4888. *offset = n - idx;
  4889. return sg;
  4890. lookup:
  4891. rcu_read_lock();
  4892. sg = radix_tree_lookup(&iter->radix, n);
  4893. GEM_BUG_ON(!sg);
  4894. /* If this index is in the middle of multi-page sg entry,
  4895. * the radixtree will contain an exceptional entry that points
  4896. * to the start of that range. We will return the pointer to
  4897. * the base page and the offset of this page within the
  4898. * sg entry's range.
  4899. */
  4900. *offset = 0;
  4901. if (unlikely(radix_tree_exception(sg))) {
  4902. unsigned long base =
  4903. (unsigned long)sg >> RADIX_TREE_EXCEPTIONAL_SHIFT;
  4904. sg = radix_tree_lookup(&iter->radix, base);
  4905. GEM_BUG_ON(!sg);
  4906. *offset = n - base;
  4907. }
  4908. rcu_read_unlock();
  4909. return sg;
  4910. }
  4911. struct page *
  4912. i915_gem_object_get_page(struct drm_i915_gem_object *obj, unsigned int n)
  4913. {
  4914. struct scatterlist *sg;
  4915. unsigned int offset;
  4916. GEM_BUG_ON(!i915_gem_object_has_struct_page(obj));
  4917. sg = i915_gem_object_get_sg(obj, n, &offset);
  4918. return nth_page(sg_page(sg), offset);
  4919. }
  4920. /* Like i915_gem_object_get_page(), but mark the returned page dirty */
  4921. struct page *
  4922. i915_gem_object_get_dirty_page(struct drm_i915_gem_object *obj,
  4923. unsigned int n)
  4924. {
  4925. struct page *page;
  4926. page = i915_gem_object_get_page(obj, n);
  4927. if (!obj->mm.dirty)
  4928. set_page_dirty(page);
  4929. return page;
  4930. }
  4931. dma_addr_t
  4932. i915_gem_object_get_dma_address(struct drm_i915_gem_object *obj,
  4933. unsigned long n)
  4934. {
  4935. struct scatterlist *sg;
  4936. unsigned int offset;
  4937. sg = i915_gem_object_get_sg(obj, n, &offset);
  4938. return sg_dma_address(sg) + (offset << PAGE_SHIFT);
  4939. }
  4940. int i915_gem_object_attach_phys(struct drm_i915_gem_object *obj, int align)
  4941. {
  4942. struct sg_table *pages;
  4943. int err;
  4944. if (align > obj->base.size)
  4945. return -EINVAL;
  4946. if (obj->ops == &i915_gem_phys_ops)
  4947. return 0;
  4948. if (obj->ops != &i915_gem_object_ops)
  4949. return -EINVAL;
  4950. err = i915_gem_object_unbind(obj);
  4951. if (err)
  4952. return err;
  4953. mutex_lock(&obj->mm.lock);
  4954. if (obj->mm.madv != I915_MADV_WILLNEED) {
  4955. err = -EFAULT;
  4956. goto err_unlock;
  4957. }
  4958. if (obj->mm.quirked) {
  4959. err = -EFAULT;
  4960. goto err_unlock;
  4961. }
  4962. if (obj->mm.mapping) {
  4963. err = -EBUSY;
  4964. goto err_unlock;
  4965. }
  4966. pages = fetch_and_zero(&obj->mm.pages);
  4967. if (pages) {
  4968. struct drm_i915_private *i915 = to_i915(obj->base.dev);
  4969. __i915_gem_object_reset_page_iter(obj);
  4970. spin_lock(&i915->mm.obj_lock);
  4971. list_del(&obj->mm.link);
  4972. spin_unlock(&i915->mm.obj_lock);
  4973. }
  4974. obj->ops = &i915_gem_phys_ops;
  4975. err = ____i915_gem_object_get_pages(obj);
  4976. if (err)
  4977. goto err_xfer;
  4978. /* Perma-pin (until release) the physical set of pages */
  4979. __i915_gem_object_pin_pages(obj);
  4980. if (!IS_ERR_OR_NULL(pages))
  4981. i915_gem_object_ops.put_pages(obj, pages);
  4982. mutex_unlock(&obj->mm.lock);
  4983. return 0;
  4984. err_xfer:
  4985. obj->ops = &i915_gem_object_ops;
  4986. obj->mm.pages = pages;
  4987. err_unlock:
  4988. mutex_unlock(&obj->mm.lock);
  4989. return err;
  4990. }
  4991. #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
  4992. #include "selftests/scatterlist.c"
  4993. #include "selftests/mock_gem_device.c"
  4994. #include "selftests/huge_gem_object.c"
  4995. #include "selftests/huge_pages.c"
  4996. #include "selftests/i915_gem_object.c"
  4997. #include "selftests/i915_gem_coherency.c"
  4998. #endif