i915_gem.c 160 KB

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