i915_gem.c 164 KB

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