i915_gem.c 163 KB

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