i915_gem.c 138 KB

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