i915_gem.c 162 KB

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