i915_gem.c 166 KB

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