i915_gem.c 164 KB

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