kvm_main.c 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434
  1. /*
  2. * Kernel-based Virtual Machine driver for Linux
  3. *
  4. * This module enables machines with Intel VT-x extensions to run virtual
  5. * machines without emulation or binary translation.
  6. *
  7. * Copyright (C) 2006 Qumranet, Inc.
  8. * Copyright 2010 Red Hat, Inc. and/or its affiliates.
  9. *
  10. * Authors:
  11. * Avi Kivity <avi@qumranet.com>
  12. * Yaniv Kamay <yaniv@qumranet.com>
  13. *
  14. * This work is licensed under the terms of the GNU GPL, version 2. See
  15. * the COPYING file in the top-level directory.
  16. *
  17. */
  18. #include <kvm/iodev.h>
  19. #include <linux/kvm_host.h>
  20. #include <linux/kvm.h>
  21. #include <linux/module.h>
  22. #include <linux/errno.h>
  23. #include <linux/percpu.h>
  24. #include <linux/mm.h>
  25. #include <linux/miscdevice.h>
  26. #include <linux/vmalloc.h>
  27. #include <linux/reboot.h>
  28. #include <linux/debugfs.h>
  29. #include <linux/highmem.h>
  30. #include <linux/file.h>
  31. #include <linux/syscore_ops.h>
  32. #include <linux/cpu.h>
  33. #include <linux/sched/signal.h>
  34. #include <linux/sched/mm.h>
  35. #include <linux/sched/stat.h>
  36. #include <linux/cpumask.h>
  37. #include <linux/smp.h>
  38. #include <linux/anon_inodes.h>
  39. #include <linux/profile.h>
  40. #include <linux/kvm_para.h>
  41. #include <linux/pagemap.h>
  42. #include <linux/mman.h>
  43. #include <linux/swap.h>
  44. #include <linux/bitops.h>
  45. #include <linux/spinlock.h>
  46. #include <linux/compat.h>
  47. #include <linux/srcu.h>
  48. #include <linux/hugetlb.h>
  49. #include <linux/slab.h>
  50. #include <linux/sort.h>
  51. #include <linux/bsearch.h>
  52. #include <linux/kthread.h>
  53. #include <linux/io.h>
  54. #include <asm/processor.h>
  55. #include <asm/ioctl.h>
  56. #include <linux/uaccess.h>
  57. #include <asm/pgtable.h>
  58. #include "coalesced_mmio.h"
  59. #include "async_pf.h"
  60. #include "vfio.h"
  61. #define CREATE_TRACE_POINTS
  62. #include <trace/events/kvm.h>
  63. /* Worst case buffer size needed for holding an integer. */
  64. #define ITOA_MAX_LEN 12
  65. MODULE_AUTHOR("Qumranet");
  66. MODULE_LICENSE("GPL");
  67. /* Architectures should define their poll value according to the halt latency */
  68. unsigned int halt_poll_ns = KVM_HALT_POLL_NS_DEFAULT;
  69. module_param(halt_poll_ns, uint, 0644);
  70. EXPORT_SYMBOL_GPL(halt_poll_ns);
  71. /* Default doubles per-vcpu halt_poll_ns. */
  72. unsigned int halt_poll_ns_grow = 2;
  73. module_param(halt_poll_ns_grow, uint, 0644);
  74. EXPORT_SYMBOL_GPL(halt_poll_ns_grow);
  75. /* Default resets per-vcpu halt_poll_ns . */
  76. unsigned int halt_poll_ns_shrink;
  77. module_param(halt_poll_ns_shrink, uint, 0644);
  78. EXPORT_SYMBOL_GPL(halt_poll_ns_shrink);
  79. /*
  80. * Ordering of locks:
  81. *
  82. * kvm->lock --> kvm->slots_lock --> kvm->irq_lock
  83. */
  84. DEFINE_MUTEX(kvm_lock);
  85. static DEFINE_RAW_SPINLOCK(kvm_count_lock);
  86. LIST_HEAD(vm_list);
  87. static cpumask_var_t cpus_hardware_enabled;
  88. static int kvm_usage_count;
  89. static atomic_t hardware_enable_failed;
  90. struct kmem_cache *kvm_vcpu_cache;
  91. EXPORT_SYMBOL_GPL(kvm_vcpu_cache);
  92. static __read_mostly struct preempt_ops kvm_preempt_ops;
  93. struct dentry *kvm_debugfs_dir;
  94. EXPORT_SYMBOL_GPL(kvm_debugfs_dir);
  95. static int kvm_debugfs_num_entries;
  96. static const struct file_operations *stat_fops_per_vm[];
  97. static long kvm_vcpu_ioctl(struct file *file, unsigned int ioctl,
  98. unsigned long arg);
  99. #ifdef CONFIG_KVM_COMPAT
  100. static long kvm_vcpu_compat_ioctl(struct file *file, unsigned int ioctl,
  101. unsigned long arg);
  102. #define KVM_COMPAT(c) .compat_ioctl = (c)
  103. #else
  104. static long kvm_no_compat_ioctl(struct file *file, unsigned int ioctl,
  105. unsigned long arg) { return -EINVAL; }
  106. #define KVM_COMPAT(c) .compat_ioctl = kvm_no_compat_ioctl
  107. #endif
  108. static int hardware_enable_all(void);
  109. static void hardware_disable_all(void);
  110. static void kvm_io_bus_destroy(struct kvm_io_bus *bus);
  111. static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot, gfn_t gfn);
  112. __visible bool kvm_rebooting;
  113. EXPORT_SYMBOL_GPL(kvm_rebooting);
  114. static bool largepages_enabled = true;
  115. #define KVM_EVENT_CREATE_VM 0
  116. #define KVM_EVENT_DESTROY_VM 1
  117. static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm);
  118. static unsigned long long kvm_createvm_count;
  119. static unsigned long long kvm_active_vms;
  120. __weak void kvm_arch_mmu_notifier_invalidate_range(struct kvm *kvm,
  121. unsigned long start, unsigned long end)
  122. {
  123. }
  124. bool kvm_is_zone_device_pfn(kvm_pfn_t pfn)
  125. {
  126. /*
  127. * The metadata used by is_zone_device_page() to determine whether or
  128. * not a page is ZONE_DEVICE is guaranteed to be valid if and only if
  129. * the device has been pinned, e.g. by get_user_pages(). WARN if the
  130. * page_count() is zero to help detect bad usage of this helper.
  131. */
  132. if (!pfn_valid(pfn) || WARN_ON_ONCE(!page_count(pfn_to_page(pfn))))
  133. return false;
  134. return is_zone_device_page(pfn_to_page(pfn));
  135. }
  136. bool kvm_is_reserved_pfn(kvm_pfn_t pfn)
  137. {
  138. /*
  139. * ZONE_DEVICE pages currently set PG_reserved, but from a refcounting
  140. * perspective they are "normal" pages, albeit with slightly different
  141. * usage rules.
  142. */
  143. if (pfn_valid(pfn))
  144. return PageReserved(pfn_to_page(pfn)) &&
  145. !is_zero_pfn(pfn) &&
  146. !kvm_is_zone_device_pfn(pfn);
  147. return true;
  148. }
  149. /*
  150. * Switches to specified vcpu, until a matching vcpu_put()
  151. */
  152. void vcpu_load(struct kvm_vcpu *vcpu)
  153. {
  154. int cpu = get_cpu();
  155. preempt_notifier_register(&vcpu->preempt_notifier);
  156. kvm_arch_vcpu_load(vcpu, cpu);
  157. put_cpu();
  158. }
  159. EXPORT_SYMBOL_GPL(vcpu_load);
  160. void vcpu_put(struct kvm_vcpu *vcpu)
  161. {
  162. preempt_disable();
  163. kvm_arch_vcpu_put(vcpu);
  164. preempt_notifier_unregister(&vcpu->preempt_notifier);
  165. preempt_enable();
  166. }
  167. EXPORT_SYMBOL_GPL(vcpu_put);
  168. /* TODO: merge with kvm_arch_vcpu_should_kick */
  169. static bool kvm_request_needs_ipi(struct kvm_vcpu *vcpu, unsigned req)
  170. {
  171. int mode = kvm_vcpu_exiting_guest_mode(vcpu);
  172. /*
  173. * We need to wait for the VCPU to reenable interrupts and get out of
  174. * READING_SHADOW_PAGE_TABLES mode.
  175. */
  176. if (req & KVM_REQUEST_WAIT)
  177. return mode != OUTSIDE_GUEST_MODE;
  178. /*
  179. * Need to kick a running VCPU, but otherwise there is nothing to do.
  180. */
  181. return mode == IN_GUEST_MODE;
  182. }
  183. static void ack_flush(void *_completed)
  184. {
  185. }
  186. static inline bool kvm_kick_many_cpus(const struct cpumask *cpus, bool wait)
  187. {
  188. if (unlikely(!cpus))
  189. cpus = cpu_online_mask;
  190. if (cpumask_empty(cpus))
  191. return false;
  192. smp_call_function_many(cpus, ack_flush, NULL, wait);
  193. return true;
  194. }
  195. bool kvm_make_vcpus_request_mask(struct kvm *kvm, unsigned int req,
  196. unsigned long *vcpu_bitmap, cpumask_var_t tmp)
  197. {
  198. int i, cpu, me;
  199. struct kvm_vcpu *vcpu;
  200. bool called;
  201. me = get_cpu();
  202. kvm_for_each_vcpu(i, vcpu, kvm) {
  203. if (!test_bit(i, vcpu_bitmap))
  204. continue;
  205. kvm_make_request(req, vcpu);
  206. cpu = vcpu->cpu;
  207. if (!(req & KVM_REQUEST_NO_WAKEUP) && kvm_vcpu_wake_up(vcpu))
  208. continue;
  209. if (tmp != NULL && cpu != -1 && cpu != me &&
  210. kvm_request_needs_ipi(vcpu, req))
  211. __cpumask_set_cpu(cpu, tmp);
  212. }
  213. called = kvm_kick_many_cpus(tmp, !!(req & KVM_REQUEST_WAIT));
  214. put_cpu();
  215. return called;
  216. }
  217. bool kvm_make_all_cpus_request(struct kvm *kvm, unsigned int req)
  218. {
  219. cpumask_var_t cpus;
  220. bool called;
  221. static unsigned long vcpu_bitmap[BITS_TO_LONGS(KVM_MAX_VCPUS)]
  222. = {[0 ... BITS_TO_LONGS(KVM_MAX_VCPUS)-1] = ULONG_MAX};
  223. zalloc_cpumask_var(&cpus, GFP_ATOMIC);
  224. called = kvm_make_vcpus_request_mask(kvm, req, vcpu_bitmap, cpus);
  225. free_cpumask_var(cpus);
  226. return called;
  227. }
  228. #ifndef CONFIG_HAVE_KVM_ARCH_TLB_FLUSH_ALL
  229. void kvm_flush_remote_tlbs(struct kvm *kvm)
  230. {
  231. /*
  232. * Read tlbs_dirty before setting KVM_REQ_TLB_FLUSH in
  233. * kvm_make_all_cpus_request.
  234. */
  235. long dirty_count = smp_load_acquire(&kvm->tlbs_dirty);
  236. /*
  237. * We want to publish modifications to the page tables before reading
  238. * mode. Pairs with a memory barrier in arch-specific code.
  239. * - x86: smp_mb__after_srcu_read_unlock in vcpu_enter_guest
  240. * and smp_mb in walk_shadow_page_lockless_begin/end.
  241. * - powerpc: smp_mb in kvmppc_prepare_to_enter.
  242. *
  243. * There is already an smp_mb__after_atomic() before
  244. * kvm_make_all_cpus_request() reads vcpu->mode. We reuse that
  245. * barrier here.
  246. */
  247. if (!kvm_arch_flush_remote_tlb(kvm)
  248. || kvm_make_all_cpus_request(kvm, KVM_REQ_TLB_FLUSH))
  249. ++kvm->stat.remote_tlb_flush;
  250. cmpxchg(&kvm->tlbs_dirty, dirty_count, 0);
  251. }
  252. EXPORT_SYMBOL_GPL(kvm_flush_remote_tlbs);
  253. #endif
  254. void kvm_reload_remote_mmus(struct kvm *kvm)
  255. {
  256. kvm_make_all_cpus_request(kvm, KVM_REQ_MMU_RELOAD);
  257. }
  258. int kvm_vcpu_init(struct kvm_vcpu *vcpu, struct kvm *kvm, unsigned id)
  259. {
  260. struct page *page;
  261. int r;
  262. mutex_init(&vcpu->mutex);
  263. vcpu->cpu = -1;
  264. vcpu->kvm = kvm;
  265. vcpu->vcpu_id = id;
  266. vcpu->pid = NULL;
  267. init_swait_queue_head(&vcpu->wq);
  268. kvm_async_pf_vcpu_init(vcpu);
  269. vcpu->pre_pcpu = -1;
  270. INIT_LIST_HEAD(&vcpu->blocked_vcpu_list);
  271. page = alloc_page(GFP_KERNEL | __GFP_ZERO);
  272. if (!page) {
  273. r = -ENOMEM;
  274. goto fail;
  275. }
  276. vcpu->run = page_address(page);
  277. kvm_vcpu_set_in_spin_loop(vcpu, false);
  278. kvm_vcpu_set_dy_eligible(vcpu, false);
  279. vcpu->preempted = false;
  280. r = kvm_arch_vcpu_init(vcpu);
  281. if (r < 0)
  282. goto fail_free_run;
  283. return 0;
  284. fail_free_run:
  285. free_page((unsigned long)vcpu->run);
  286. fail:
  287. return r;
  288. }
  289. EXPORT_SYMBOL_GPL(kvm_vcpu_init);
  290. void kvm_vcpu_uninit(struct kvm_vcpu *vcpu)
  291. {
  292. /*
  293. * no need for rcu_read_lock as VCPU_RUN is the only place that
  294. * will change the vcpu->pid pointer and on uninit all file
  295. * descriptors are already gone.
  296. */
  297. put_pid(rcu_dereference_protected(vcpu->pid, 1));
  298. kvm_arch_vcpu_uninit(vcpu);
  299. free_page((unsigned long)vcpu->run);
  300. }
  301. EXPORT_SYMBOL_GPL(kvm_vcpu_uninit);
  302. #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
  303. static inline struct kvm *mmu_notifier_to_kvm(struct mmu_notifier *mn)
  304. {
  305. return container_of(mn, struct kvm, mmu_notifier);
  306. }
  307. static void kvm_mmu_notifier_invalidate_range(struct mmu_notifier *mn,
  308. struct mm_struct *mm,
  309. unsigned long start, unsigned long end)
  310. {
  311. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  312. int idx;
  313. idx = srcu_read_lock(&kvm->srcu);
  314. kvm_arch_mmu_notifier_invalidate_range(kvm, start, end);
  315. srcu_read_unlock(&kvm->srcu, idx);
  316. }
  317. static void kvm_mmu_notifier_change_pte(struct mmu_notifier *mn,
  318. struct mm_struct *mm,
  319. unsigned long address,
  320. pte_t pte)
  321. {
  322. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  323. int idx;
  324. idx = srcu_read_lock(&kvm->srcu);
  325. spin_lock(&kvm->mmu_lock);
  326. kvm->mmu_notifier_seq++;
  327. kvm_set_spte_hva(kvm, address, pte);
  328. spin_unlock(&kvm->mmu_lock);
  329. srcu_read_unlock(&kvm->srcu, idx);
  330. }
  331. static int kvm_mmu_notifier_invalidate_range_start(struct mmu_notifier *mn,
  332. struct mm_struct *mm,
  333. unsigned long start,
  334. unsigned long end,
  335. bool blockable)
  336. {
  337. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  338. int need_tlb_flush = 0, idx;
  339. idx = srcu_read_lock(&kvm->srcu);
  340. spin_lock(&kvm->mmu_lock);
  341. /*
  342. * The count increase must become visible at unlock time as no
  343. * spte can be established without taking the mmu_lock and
  344. * count is also read inside the mmu_lock critical section.
  345. */
  346. kvm->mmu_notifier_count++;
  347. need_tlb_flush = kvm_unmap_hva_range(kvm, start, end, blockable);
  348. /* we've to flush the tlb before the pages can be freed */
  349. if (need_tlb_flush || kvm->tlbs_dirty)
  350. kvm_flush_remote_tlbs(kvm);
  351. spin_unlock(&kvm->mmu_lock);
  352. srcu_read_unlock(&kvm->srcu, idx);
  353. return 0;
  354. }
  355. static void kvm_mmu_notifier_invalidate_range_end(struct mmu_notifier *mn,
  356. struct mm_struct *mm,
  357. unsigned long start,
  358. unsigned long end)
  359. {
  360. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  361. spin_lock(&kvm->mmu_lock);
  362. /*
  363. * This sequence increase will notify the kvm page fault that
  364. * the page that is going to be mapped in the spte could have
  365. * been freed.
  366. */
  367. kvm->mmu_notifier_seq++;
  368. smp_wmb();
  369. /*
  370. * The above sequence increase must be visible before the
  371. * below count decrease, which is ensured by the smp_wmb above
  372. * in conjunction with the smp_rmb in mmu_notifier_retry().
  373. */
  374. kvm->mmu_notifier_count--;
  375. spin_unlock(&kvm->mmu_lock);
  376. BUG_ON(kvm->mmu_notifier_count < 0);
  377. }
  378. static int kvm_mmu_notifier_clear_flush_young(struct mmu_notifier *mn,
  379. struct mm_struct *mm,
  380. unsigned long start,
  381. unsigned long end)
  382. {
  383. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  384. int young, idx;
  385. idx = srcu_read_lock(&kvm->srcu);
  386. spin_lock(&kvm->mmu_lock);
  387. young = kvm_age_hva(kvm, start, end);
  388. if (young)
  389. kvm_flush_remote_tlbs(kvm);
  390. spin_unlock(&kvm->mmu_lock);
  391. srcu_read_unlock(&kvm->srcu, idx);
  392. return young;
  393. }
  394. static int kvm_mmu_notifier_clear_young(struct mmu_notifier *mn,
  395. struct mm_struct *mm,
  396. unsigned long start,
  397. unsigned long end)
  398. {
  399. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  400. int young, idx;
  401. idx = srcu_read_lock(&kvm->srcu);
  402. spin_lock(&kvm->mmu_lock);
  403. /*
  404. * Even though we do not flush TLB, this will still adversely
  405. * affect performance on pre-Haswell Intel EPT, where there is
  406. * no EPT Access Bit to clear so that we have to tear down EPT
  407. * tables instead. If we find this unacceptable, we can always
  408. * add a parameter to kvm_age_hva so that it effectively doesn't
  409. * do anything on clear_young.
  410. *
  411. * Also note that currently we never issue secondary TLB flushes
  412. * from clear_young, leaving this job up to the regular system
  413. * cadence. If we find this inaccurate, we might come up with a
  414. * more sophisticated heuristic later.
  415. */
  416. young = kvm_age_hva(kvm, start, end);
  417. spin_unlock(&kvm->mmu_lock);
  418. srcu_read_unlock(&kvm->srcu, idx);
  419. return young;
  420. }
  421. static int kvm_mmu_notifier_test_young(struct mmu_notifier *mn,
  422. struct mm_struct *mm,
  423. unsigned long address)
  424. {
  425. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  426. int young, idx;
  427. idx = srcu_read_lock(&kvm->srcu);
  428. spin_lock(&kvm->mmu_lock);
  429. young = kvm_test_age_hva(kvm, address);
  430. spin_unlock(&kvm->mmu_lock);
  431. srcu_read_unlock(&kvm->srcu, idx);
  432. return young;
  433. }
  434. static void kvm_mmu_notifier_release(struct mmu_notifier *mn,
  435. struct mm_struct *mm)
  436. {
  437. struct kvm *kvm = mmu_notifier_to_kvm(mn);
  438. int idx;
  439. idx = srcu_read_lock(&kvm->srcu);
  440. kvm_arch_flush_shadow_all(kvm);
  441. srcu_read_unlock(&kvm->srcu, idx);
  442. }
  443. static const struct mmu_notifier_ops kvm_mmu_notifier_ops = {
  444. .flags = MMU_INVALIDATE_DOES_NOT_BLOCK,
  445. .invalidate_range = kvm_mmu_notifier_invalidate_range,
  446. .invalidate_range_start = kvm_mmu_notifier_invalidate_range_start,
  447. .invalidate_range_end = kvm_mmu_notifier_invalidate_range_end,
  448. .clear_flush_young = kvm_mmu_notifier_clear_flush_young,
  449. .clear_young = kvm_mmu_notifier_clear_young,
  450. .test_young = kvm_mmu_notifier_test_young,
  451. .change_pte = kvm_mmu_notifier_change_pte,
  452. .release = kvm_mmu_notifier_release,
  453. };
  454. static int kvm_init_mmu_notifier(struct kvm *kvm)
  455. {
  456. kvm->mmu_notifier.ops = &kvm_mmu_notifier_ops;
  457. return mmu_notifier_register(&kvm->mmu_notifier, current->mm);
  458. }
  459. #else /* !(CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER) */
  460. static int kvm_init_mmu_notifier(struct kvm *kvm)
  461. {
  462. return 0;
  463. }
  464. #endif /* CONFIG_MMU_NOTIFIER && KVM_ARCH_WANT_MMU_NOTIFIER */
  465. static struct kvm_memslots *kvm_alloc_memslots(void)
  466. {
  467. int i;
  468. struct kvm_memslots *slots;
  469. slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
  470. if (!slots)
  471. return NULL;
  472. for (i = 0; i < KVM_MEM_SLOTS_NUM; i++)
  473. slots->id_to_index[i] = slots->memslots[i].id = i;
  474. return slots;
  475. }
  476. static void kvm_destroy_dirty_bitmap(struct kvm_memory_slot *memslot)
  477. {
  478. if (!memslot->dirty_bitmap)
  479. return;
  480. kvfree(memslot->dirty_bitmap);
  481. memslot->dirty_bitmap = NULL;
  482. }
  483. /*
  484. * Free any memory in @free but not in @dont.
  485. */
  486. static void kvm_free_memslot(struct kvm *kvm, struct kvm_memory_slot *free,
  487. struct kvm_memory_slot *dont)
  488. {
  489. if (!dont || free->dirty_bitmap != dont->dirty_bitmap)
  490. kvm_destroy_dirty_bitmap(free);
  491. kvm_arch_free_memslot(kvm, free, dont);
  492. free->npages = 0;
  493. }
  494. static void kvm_free_memslots(struct kvm *kvm, struct kvm_memslots *slots)
  495. {
  496. struct kvm_memory_slot *memslot;
  497. if (!slots)
  498. return;
  499. kvm_for_each_memslot(memslot, slots)
  500. kvm_free_memslot(kvm, memslot, NULL);
  501. kvfree(slots);
  502. }
  503. static void kvm_destroy_vm_debugfs(struct kvm *kvm)
  504. {
  505. int i;
  506. if (!kvm->debugfs_dentry)
  507. return;
  508. debugfs_remove_recursive(kvm->debugfs_dentry);
  509. if (kvm->debugfs_stat_data) {
  510. for (i = 0; i < kvm_debugfs_num_entries; i++)
  511. kfree(kvm->debugfs_stat_data[i]);
  512. kfree(kvm->debugfs_stat_data);
  513. }
  514. }
  515. static int kvm_create_vm_debugfs(struct kvm *kvm, int fd)
  516. {
  517. char dir_name[ITOA_MAX_LEN * 2];
  518. struct kvm_stat_data *stat_data;
  519. struct kvm_stats_debugfs_item *p;
  520. if (!debugfs_initialized())
  521. return 0;
  522. snprintf(dir_name, sizeof(dir_name), "%d-%d", task_pid_nr(current), fd);
  523. kvm->debugfs_dentry = debugfs_create_dir(dir_name, kvm_debugfs_dir);
  524. kvm->debugfs_stat_data = kcalloc(kvm_debugfs_num_entries,
  525. sizeof(*kvm->debugfs_stat_data),
  526. GFP_KERNEL);
  527. if (!kvm->debugfs_stat_data)
  528. return -ENOMEM;
  529. for (p = debugfs_entries; p->name; p++) {
  530. stat_data = kzalloc(sizeof(*stat_data), GFP_KERNEL);
  531. if (!stat_data)
  532. return -ENOMEM;
  533. stat_data->kvm = kvm;
  534. stat_data->offset = p->offset;
  535. stat_data->mode = p->mode ? p->mode : 0644;
  536. kvm->debugfs_stat_data[p - debugfs_entries] = stat_data;
  537. debugfs_create_file(p->name, stat_data->mode, kvm->debugfs_dentry,
  538. stat_data, stat_fops_per_vm[p->kind]);
  539. }
  540. return 0;
  541. }
  542. /*
  543. * Called after the VM is otherwise initialized, but just before adding it to
  544. * the vm_list.
  545. */
  546. int __weak kvm_arch_post_init_vm(struct kvm *kvm)
  547. {
  548. return 0;
  549. }
  550. /*
  551. * Called just after removing the VM from the vm_list, but before doing any
  552. * other destruction.
  553. */
  554. void __weak kvm_arch_pre_destroy_vm(struct kvm *kvm)
  555. {
  556. }
  557. static struct kvm *kvm_create_vm(unsigned long type)
  558. {
  559. int r, i;
  560. struct kvm *kvm = kvm_arch_alloc_vm();
  561. if (!kvm)
  562. return ERR_PTR(-ENOMEM);
  563. spin_lock_init(&kvm->mmu_lock);
  564. mmgrab(current->mm);
  565. kvm->mm = current->mm;
  566. kvm_eventfd_init(kvm);
  567. mutex_init(&kvm->lock);
  568. mutex_init(&kvm->irq_lock);
  569. mutex_init(&kvm->slots_lock);
  570. refcount_set(&kvm->users_count, 1);
  571. INIT_LIST_HEAD(&kvm->devices);
  572. r = kvm_arch_init_vm(kvm, type);
  573. if (r)
  574. goto out_err_no_disable;
  575. r = hardware_enable_all();
  576. if (r)
  577. goto out_err_no_disable;
  578. #ifdef CONFIG_HAVE_KVM_IRQFD
  579. INIT_HLIST_HEAD(&kvm->irq_ack_notifier_list);
  580. #endif
  581. BUILD_BUG_ON(KVM_MEM_SLOTS_NUM > SHRT_MAX);
  582. r = -ENOMEM;
  583. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++) {
  584. struct kvm_memslots *slots = kvm_alloc_memslots();
  585. if (!slots)
  586. goto out_err_no_srcu;
  587. /*
  588. * Generations must be different for each address space.
  589. * Init kvm generation close to the maximum to easily test the
  590. * code of handling generation number wrap-around.
  591. */
  592. slots->generation = i * 2 - 150;
  593. rcu_assign_pointer(kvm->memslots[i], slots);
  594. }
  595. if (init_srcu_struct(&kvm->srcu))
  596. goto out_err_no_srcu;
  597. if (init_srcu_struct(&kvm->irq_srcu))
  598. goto out_err_no_irq_srcu;
  599. for (i = 0; i < KVM_NR_BUSES; i++) {
  600. rcu_assign_pointer(kvm->buses[i],
  601. kzalloc(sizeof(struct kvm_io_bus), GFP_KERNEL));
  602. if (!kvm->buses[i])
  603. goto out_err_no_mmu_notifier;
  604. }
  605. r = kvm_init_mmu_notifier(kvm);
  606. if (r)
  607. goto out_err_no_mmu_notifier;
  608. r = kvm_arch_post_init_vm(kvm);
  609. if (r)
  610. goto out_err;
  611. mutex_lock(&kvm_lock);
  612. list_add(&kvm->vm_list, &vm_list);
  613. mutex_unlock(&kvm_lock);
  614. preempt_notifier_inc();
  615. return kvm;
  616. out_err:
  617. #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
  618. if (kvm->mmu_notifier.ops)
  619. mmu_notifier_unregister(&kvm->mmu_notifier, current->mm);
  620. #endif
  621. out_err_no_mmu_notifier:
  622. cleanup_srcu_struct(&kvm->irq_srcu);
  623. out_err_no_irq_srcu:
  624. cleanup_srcu_struct(&kvm->srcu);
  625. out_err_no_srcu:
  626. hardware_disable_all();
  627. out_err_no_disable:
  628. refcount_set(&kvm->users_count, 0);
  629. for (i = 0; i < KVM_NR_BUSES; i++)
  630. kfree(kvm_get_bus(kvm, i));
  631. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
  632. kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
  633. kvm_arch_free_vm(kvm);
  634. mmdrop(current->mm);
  635. return ERR_PTR(r);
  636. }
  637. static void kvm_destroy_devices(struct kvm *kvm)
  638. {
  639. struct kvm_device *dev, *tmp;
  640. /*
  641. * We do not need to take the kvm->lock here, because nobody else
  642. * has a reference to the struct kvm at this point and therefore
  643. * cannot access the devices list anyhow.
  644. */
  645. list_for_each_entry_safe(dev, tmp, &kvm->devices, vm_node) {
  646. list_del(&dev->vm_node);
  647. dev->ops->destroy(dev);
  648. }
  649. }
  650. static void kvm_destroy_vm(struct kvm *kvm)
  651. {
  652. int i;
  653. struct mm_struct *mm = kvm->mm;
  654. kvm_uevent_notify_change(KVM_EVENT_DESTROY_VM, kvm);
  655. kvm_destroy_vm_debugfs(kvm);
  656. kvm_arch_sync_events(kvm);
  657. mutex_lock(&kvm_lock);
  658. list_del(&kvm->vm_list);
  659. mutex_unlock(&kvm_lock);
  660. kvm_arch_pre_destroy_vm(kvm);
  661. kvm_free_irq_routing(kvm);
  662. for (i = 0; i < KVM_NR_BUSES; i++) {
  663. struct kvm_io_bus *bus = kvm_get_bus(kvm, i);
  664. if (bus)
  665. kvm_io_bus_destroy(bus);
  666. kvm->buses[i] = NULL;
  667. }
  668. kvm_coalesced_mmio_free(kvm);
  669. #if defined(CONFIG_MMU_NOTIFIER) && defined(KVM_ARCH_WANT_MMU_NOTIFIER)
  670. mmu_notifier_unregister(&kvm->mmu_notifier, kvm->mm);
  671. #else
  672. kvm_arch_flush_shadow_all(kvm);
  673. #endif
  674. kvm_arch_destroy_vm(kvm);
  675. kvm_destroy_devices(kvm);
  676. for (i = 0; i < KVM_ADDRESS_SPACE_NUM; i++)
  677. kvm_free_memslots(kvm, __kvm_memslots(kvm, i));
  678. cleanup_srcu_struct(&kvm->irq_srcu);
  679. cleanup_srcu_struct(&kvm->srcu);
  680. kvm_arch_free_vm(kvm);
  681. preempt_notifier_dec();
  682. hardware_disable_all();
  683. mmdrop(mm);
  684. }
  685. void kvm_get_kvm(struct kvm *kvm)
  686. {
  687. refcount_inc(&kvm->users_count);
  688. }
  689. EXPORT_SYMBOL_GPL(kvm_get_kvm);
  690. void kvm_put_kvm(struct kvm *kvm)
  691. {
  692. if (refcount_dec_and_test(&kvm->users_count))
  693. kvm_destroy_vm(kvm);
  694. }
  695. EXPORT_SYMBOL_GPL(kvm_put_kvm);
  696. static int kvm_vm_release(struct inode *inode, struct file *filp)
  697. {
  698. struct kvm *kvm = filp->private_data;
  699. kvm_irqfd_release(kvm);
  700. kvm_put_kvm(kvm);
  701. return 0;
  702. }
  703. /*
  704. * Allocation size is twice as large as the actual dirty bitmap size.
  705. * See x86's kvm_vm_ioctl_get_dirty_log() why this is needed.
  706. */
  707. static int kvm_create_dirty_bitmap(struct kvm_memory_slot *memslot)
  708. {
  709. unsigned long dirty_bytes = 2 * kvm_dirty_bitmap_bytes(memslot);
  710. memslot->dirty_bitmap = kvzalloc(dirty_bytes, GFP_KERNEL);
  711. if (!memslot->dirty_bitmap)
  712. return -ENOMEM;
  713. return 0;
  714. }
  715. /*
  716. * Insert memslot and re-sort memslots based on their GFN,
  717. * so binary search could be used to lookup GFN.
  718. * Sorting algorithm takes advantage of having initially
  719. * sorted array and known changed memslot position.
  720. */
  721. static void update_memslots(struct kvm_memslots *slots,
  722. struct kvm_memory_slot *new)
  723. {
  724. int id = new->id;
  725. int i = slots->id_to_index[id];
  726. struct kvm_memory_slot *mslots = slots->memslots;
  727. WARN_ON(mslots[i].id != id);
  728. if (!new->npages) {
  729. WARN_ON(!mslots[i].npages);
  730. if (mslots[i].npages)
  731. slots->used_slots--;
  732. } else {
  733. if (!mslots[i].npages)
  734. slots->used_slots++;
  735. }
  736. while (i < KVM_MEM_SLOTS_NUM - 1 &&
  737. new->base_gfn <= mslots[i + 1].base_gfn) {
  738. if (!mslots[i + 1].npages)
  739. break;
  740. mslots[i] = mslots[i + 1];
  741. slots->id_to_index[mslots[i].id] = i;
  742. i++;
  743. }
  744. /*
  745. * The ">=" is needed when creating a slot with base_gfn == 0,
  746. * so that it moves before all those with base_gfn == npages == 0.
  747. *
  748. * On the other hand, if new->npages is zero, the above loop has
  749. * already left i pointing to the beginning of the empty part of
  750. * mslots, and the ">=" would move the hole backwards in this
  751. * case---which is wrong. So skip the loop when deleting a slot.
  752. */
  753. if (new->npages) {
  754. while (i > 0 &&
  755. new->base_gfn >= mslots[i - 1].base_gfn) {
  756. mslots[i] = mslots[i - 1];
  757. slots->id_to_index[mslots[i].id] = i;
  758. i--;
  759. }
  760. } else
  761. WARN_ON_ONCE(i != slots->used_slots);
  762. mslots[i] = *new;
  763. slots->id_to_index[mslots[i].id] = i;
  764. }
  765. static int check_memory_region_flags(const struct kvm_userspace_memory_region *mem)
  766. {
  767. u32 valid_flags = KVM_MEM_LOG_DIRTY_PAGES;
  768. #ifdef __KVM_HAVE_READONLY_MEM
  769. valid_flags |= KVM_MEM_READONLY;
  770. #endif
  771. if (mem->flags & ~valid_flags)
  772. return -EINVAL;
  773. return 0;
  774. }
  775. static struct kvm_memslots *install_new_memslots(struct kvm *kvm,
  776. int as_id, struct kvm_memslots *slots)
  777. {
  778. struct kvm_memslots *old_memslots = __kvm_memslots(kvm, as_id);
  779. u64 gen;
  780. /*
  781. * Set the low bit in the generation, which disables SPTE caching
  782. * until the end of synchronize_srcu_expedited.
  783. */
  784. WARN_ON(old_memslots->generation & 1);
  785. slots->generation = old_memslots->generation + 1;
  786. rcu_assign_pointer(kvm->memslots[as_id], slots);
  787. synchronize_srcu_expedited(&kvm->srcu);
  788. /*
  789. * Increment the new memslot generation a second time. This prevents
  790. * vm exits that race with memslot updates from caching a memslot
  791. * generation that will (potentially) be valid forever.
  792. *
  793. * Generations must be unique even across address spaces. We do not need
  794. * a global counter for that, instead the generation space is evenly split
  795. * across address spaces. For example, with two address spaces, address
  796. * space 0 will use generations 0, 4, 8, ... while * address space 1 will
  797. * use generations 2, 6, 10, 14, ...
  798. */
  799. gen = slots->generation + KVM_ADDRESS_SPACE_NUM * 2 - 1;
  800. kvm_arch_memslots_updated(kvm, gen);
  801. slots->generation = gen;
  802. return old_memslots;
  803. }
  804. /*
  805. * Allocate some memory and give it an address in the guest physical address
  806. * space.
  807. *
  808. * Discontiguous memory is allowed, mostly for framebuffers.
  809. *
  810. * Must be called holding kvm->slots_lock for write.
  811. */
  812. int __kvm_set_memory_region(struct kvm *kvm,
  813. const struct kvm_userspace_memory_region *mem)
  814. {
  815. int r;
  816. gfn_t base_gfn;
  817. unsigned long npages;
  818. struct kvm_memory_slot *slot;
  819. struct kvm_memory_slot old, new;
  820. struct kvm_memslots *slots = NULL, *old_memslots;
  821. int as_id, id;
  822. enum kvm_mr_change change;
  823. r = check_memory_region_flags(mem);
  824. if (r)
  825. goto out;
  826. r = -EINVAL;
  827. as_id = mem->slot >> 16;
  828. id = (u16)mem->slot;
  829. /* General sanity checks */
  830. if (mem->memory_size & (PAGE_SIZE - 1))
  831. goto out;
  832. if (mem->guest_phys_addr & (PAGE_SIZE - 1))
  833. goto out;
  834. /* We can read the guest memory with __xxx_user() later on. */
  835. if ((id < KVM_USER_MEM_SLOTS) &&
  836. ((mem->userspace_addr & (PAGE_SIZE - 1)) ||
  837. !access_ok(VERIFY_WRITE,
  838. (void __user *)(unsigned long)mem->userspace_addr,
  839. mem->memory_size)))
  840. goto out;
  841. if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)
  842. goto out;
  843. if (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)
  844. goto out;
  845. slot = id_to_memslot(__kvm_memslots(kvm, as_id), id);
  846. base_gfn = mem->guest_phys_addr >> PAGE_SHIFT;
  847. npages = mem->memory_size >> PAGE_SHIFT;
  848. if (npages > KVM_MEM_MAX_NR_PAGES)
  849. goto out;
  850. new = old = *slot;
  851. new.id = id;
  852. new.base_gfn = base_gfn;
  853. new.npages = npages;
  854. new.flags = mem->flags;
  855. if (npages) {
  856. if (!old.npages)
  857. change = KVM_MR_CREATE;
  858. else { /* Modify an existing slot. */
  859. if ((mem->userspace_addr != old.userspace_addr) ||
  860. (npages != old.npages) ||
  861. ((new.flags ^ old.flags) & KVM_MEM_READONLY))
  862. goto out;
  863. if (base_gfn != old.base_gfn)
  864. change = KVM_MR_MOVE;
  865. else if (new.flags != old.flags)
  866. change = KVM_MR_FLAGS_ONLY;
  867. else { /* Nothing to change. */
  868. r = 0;
  869. goto out;
  870. }
  871. }
  872. } else {
  873. if (!old.npages)
  874. goto out;
  875. change = KVM_MR_DELETE;
  876. new.base_gfn = 0;
  877. new.flags = 0;
  878. }
  879. if ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {
  880. /* Check for overlaps */
  881. r = -EEXIST;
  882. kvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {
  883. if (slot->id == id)
  884. continue;
  885. if (!((base_gfn + npages <= slot->base_gfn) ||
  886. (base_gfn >= slot->base_gfn + slot->npages)))
  887. goto out;
  888. }
  889. }
  890. /* Free page dirty bitmap if unneeded */
  891. if (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))
  892. new.dirty_bitmap = NULL;
  893. r = -ENOMEM;
  894. if (change == KVM_MR_CREATE) {
  895. new.userspace_addr = mem->userspace_addr;
  896. if (kvm_arch_create_memslot(kvm, &new, npages))
  897. goto out_free;
  898. }
  899. /* Allocate page dirty bitmap if needed */
  900. if ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {
  901. if (kvm_create_dirty_bitmap(&new) < 0)
  902. goto out_free;
  903. }
  904. slots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);
  905. if (!slots)
  906. goto out_free;
  907. memcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));
  908. if ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {
  909. slot = id_to_memslot(slots, id);
  910. slot->flags |= KVM_MEMSLOT_INVALID;
  911. old_memslots = install_new_memslots(kvm, as_id, slots);
  912. /* From this point no new shadow pages pointing to a deleted,
  913. * or moved, memslot will be created.
  914. *
  915. * validation of sp->gfn happens in:
  916. * - gfn_to_hva (kvm_read_guest, gfn_to_pfn)
  917. * - kvm_is_visible_gfn (mmu_check_roots)
  918. */
  919. kvm_arch_flush_shadow_memslot(kvm, slot);
  920. /*
  921. * We can re-use the old_memslots from above, the only difference
  922. * from the currently installed memslots is the invalid flag. This
  923. * will get overwritten by update_memslots anyway.
  924. */
  925. slots = old_memslots;
  926. }
  927. r = kvm_arch_prepare_memory_region(kvm, &new, mem, change);
  928. if (r)
  929. goto out_slots;
  930. /* actual memory is freed via old in kvm_free_memslot below */
  931. if (change == KVM_MR_DELETE) {
  932. new.dirty_bitmap = NULL;
  933. memset(&new.arch, 0, sizeof(new.arch));
  934. }
  935. update_memslots(slots, &new);
  936. old_memslots = install_new_memslots(kvm, as_id, slots);
  937. kvm_arch_commit_memory_region(kvm, mem, &old, &new, change);
  938. kvm_free_memslot(kvm, &old, &new);
  939. kvfree(old_memslots);
  940. return 0;
  941. out_slots:
  942. kvfree(slots);
  943. out_free:
  944. kvm_free_memslot(kvm, &new, &old);
  945. out:
  946. return r;
  947. }
  948. EXPORT_SYMBOL_GPL(__kvm_set_memory_region);
  949. int kvm_set_memory_region(struct kvm *kvm,
  950. const struct kvm_userspace_memory_region *mem)
  951. {
  952. int r;
  953. mutex_lock(&kvm->slots_lock);
  954. r = __kvm_set_memory_region(kvm, mem);
  955. mutex_unlock(&kvm->slots_lock);
  956. return r;
  957. }
  958. EXPORT_SYMBOL_GPL(kvm_set_memory_region);
  959. static int kvm_vm_ioctl_set_memory_region(struct kvm *kvm,
  960. struct kvm_userspace_memory_region *mem)
  961. {
  962. if ((u16)mem->slot >= KVM_USER_MEM_SLOTS)
  963. return -EINVAL;
  964. return kvm_set_memory_region(kvm, mem);
  965. }
  966. int kvm_get_dirty_log(struct kvm *kvm,
  967. struct kvm_dirty_log *log, int *is_dirty)
  968. {
  969. struct kvm_memslots *slots;
  970. struct kvm_memory_slot *memslot;
  971. int i, as_id, id;
  972. unsigned long n;
  973. unsigned long any = 0;
  974. as_id = log->slot >> 16;
  975. id = (u16)log->slot;
  976. if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
  977. return -EINVAL;
  978. slots = __kvm_memslots(kvm, as_id);
  979. memslot = id_to_memslot(slots, id);
  980. if (!memslot->dirty_bitmap)
  981. return -ENOENT;
  982. n = kvm_dirty_bitmap_bytes(memslot);
  983. for (i = 0; !any && i < n/sizeof(long); ++i)
  984. any = memslot->dirty_bitmap[i];
  985. if (copy_to_user(log->dirty_bitmap, memslot->dirty_bitmap, n))
  986. return -EFAULT;
  987. if (any)
  988. *is_dirty = 1;
  989. return 0;
  990. }
  991. EXPORT_SYMBOL_GPL(kvm_get_dirty_log);
  992. #ifdef CONFIG_KVM_GENERIC_DIRTYLOG_READ_PROTECT
  993. /**
  994. * kvm_get_dirty_log_protect - get a snapshot of dirty pages, and if any pages
  995. * are dirty write protect them for next write.
  996. * @kvm: pointer to kvm instance
  997. * @log: slot id and address to which we copy the log
  998. * @is_dirty: flag set if any page is dirty
  999. *
  1000. * We need to keep it in mind that VCPU threads can write to the bitmap
  1001. * concurrently. So, to avoid losing track of dirty pages we keep the
  1002. * following order:
  1003. *
  1004. * 1. Take a snapshot of the bit and clear it if needed.
  1005. * 2. Write protect the corresponding page.
  1006. * 3. Copy the snapshot to the userspace.
  1007. * 4. Upon return caller flushes TLB's if needed.
  1008. *
  1009. * Between 2 and 4, the guest may write to the page using the remaining TLB
  1010. * entry. This is not a problem because the page is reported dirty using
  1011. * the snapshot taken before and step 4 ensures that writes done after
  1012. * exiting to userspace will be logged for the next call.
  1013. *
  1014. */
  1015. int kvm_get_dirty_log_protect(struct kvm *kvm,
  1016. struct kvm_dirty_log *log, bool *is_dirty)
  1017. {
  1018. struct kvm_memslots *slots;
  1019. struct kvm_memory_slot *memslot;
  1020. int i, as_id, id;
  1021. unsigned long n;
  1022. unsigned long *dirty_bitmap;
  1023. unsigned long *dirty_bitmap_buffer;
  1024. as_id = log->slot >> 16;
  1025. id = (u16)log->slot;
  1026. if (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_USER_MEM_SLOTS)
  1027. return -EINVAL;
  1028. slots = __kvm_memslots(kvm, as_id);
  1029. memslot = id_to_memslot(slots, id);
  1030. dirty_bitmap = memslot->dirty_bitmap;
  1031. if (!dirty_bitmap)
  1032. return -ENOENT;
  1033. n = kvm_dirty_bitmap_bytes(memslot);
  1034. dirty_bitmap_buffer = kvm_second_dirty_bitmap(memslot);
  1035. memset(dirty_bitmap_buffer, 0, n);
  1036. spin_lock(&kvm->mmu_lock);
  1037. *is_dirty = false;
  1038. for (i = 0; i < n / sizeof(long); i++) {
  1039. unsigned long mask;
  1040. gfn_t offset;
  1041. if (!dirty_bitmap[i])
  1042. continue;
  1043. *is_dirty = true;
  1044. mask = xchg(&dirty_bitmap[i], 0);
  1045. dirty_bitmap_buffer[i] = mask;
  1046. if (mask) {
  1047. offset = i * BITS_PER_LONG;
  1048. kvm_arch_mmu_enable_log_dirty_pt_masked(kvm, memslot,
  1049. offset, mask);
  1050. }
  1051. }
  1052. spin_unlock(&kvm->mmu_lock);
  1053. if (copy_to_user(log->dirty_bitmap, dirty_bitmap_buffer, n))
  1054. return -EFAULT;
  1055. return 0;
  1056. }
  1057. EXPORT_SYMBOL_GPL(kvm_get_dirty_log_protect);
  1058. #endif
  1059. bool kvm_largepages_enabled(void)
  1060. {
  1061. return largepages_enabled;
  1062. }
  1063. void kvm_disable_largepages(void)
  1064. {
  1065. largepages_enabled = false;
  1066. }
  1067. EXPORT_SYMBOL_GPL(kvm_disable_largepages);
  1068. struct kvm_memory_slot *gfn_to_memslot(struct kvm *kvm, gfn_t gfn)
  1069. {
  1070. return __gfn_to_memslot(kvm_memslots(kvm), gfn);
  1071. }
  1072. EXPORT_SYMBOL_GPL(gfn_to_memslot);
  1073. struct kvm_memory_slot *kvm_vcpu_gfn_to_memslot(struct kvm_vcpu *vcpu, gfn_t gfn)
  1074. {
  1075. return __gfn_to_memslot(kvm_vcpu_memslots(vcpu), gfn);
  1076. }
  1077. bool kvm_is_visible_gfn(struct kvm *kvm, gfn_t gfn)
  1078. {
  1079. struct kvm_memory_slot *memslot = gfn_to_memslot(kvm, gfn);
  1080. if (!memslot || memslot->id >= KVM_USER_MEM_SLOTS ||
  1081. memslot->flags & KVM_MEMSLOT_INVALID)
  1082. return false;
  1083. return true;
  1084. }
  1085. EXPORT_SYMBOL_GPL(kvm_is_visible_gfn);
  1086. unsigned long kvm_host_page_size(struct kvm_vcpu *vcpu, gfn_t gfn)
  1087. {
  1088. struct vm_area_struct *vma;
  1089. unsigned long addr, size;
  1090. size = PAGE_SIZE;
  1091. addr = kvm_vcpu_gfn_to_hva_prot(vcpu, gfn, NULL);
  1092. if (kvm_is_error_hva(addr))
  1093. return PAGE_SIZE;
  1094. down_read(&current->mm->mmap_sem);
  1095. vma = find_vma(current->mm, addr);
  1096. if (!vma)
  1097. goto out;
  1098. size = vma_kernel_pagesize(vma);
  1099. out:
  1100. up_read(&current->mm->mmap_sem);
  1101. return size;
  1102. }
  1103. static bool memslot_is_readonly(struct kvm_memory_slot *slot)
  1104. {
  1105. return slot->flags & KVM_MEM_READONLY;
  1106. }
  1107. static unsigned long __gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
  1108. gfn_t *nr_pages, bool write)
  1109. {
  1110. if (!slot || slot->flags & KVM_MEMSLOT_INVALID)
  1111. return KVM_HVA_ERR_BAD;
  1112. if (memslot_is_readonly(slot) && write)
  1113. return KVM_HVA_ERR_RO_BAD;
  1114. if (nr_pages)
  1115. *nr_pages = slot->npages - (gfn - slot->base_gfn);
  1116. return __gfn_to_hva_memslot(slot, gfn);
  1117. }
  1118. static unsigned long gfn_to_hva_many(struct kvm_memory_slot *slot, gfn_t gfn,
  1119. gfn_t *nr_pages)
  1120. {
  1121. return __gfn_to_hva_many(slot, gfn, nr_pages, true);
  1122. }
  1123. unsigned long gfn_to_hva_memslot(struct kvm_memory_slot *slot,
  1124. gfn_t gfn)
  1125. {
  1126. return gfn_to_hva_many(slot, gfn, NULL);
  1127. }
  1128. EXPORT_SYMBOL_GPL(gfn_to_hva_memslot);
  1129. unsigned long gfn_to_hva(struct kvm *kvm, gfn_t gfn)
  1130. {
  1131. return gfn_to_hva_many(gfn_to_memslot(kvm, gfn), gfn, NULL);
  1132. }
  1133. EXPORT_SYMBOL_GPL(gfn_to_hva);
  1134. unsigned long kvm_vcpu_gfn_to_hva(struct kvm_vcpu *vcpu, gfn_t gfn)
  1135. {
  1136. return gfn_to_hva_many(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn, NULL);
  1137. }
  1138. EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_hva);
  1139. /*
  1140. * If writable is set to false, the hva returned by this function is only
  1141. * allowed to be read.
  1142. */
  1143. unsigned long gfn_to_hva_memslot_prot(struct kvm_memory_slot *slot,
  1144. gfn_t gfn, bool *writable)
  1145. {
  1146. unsigned long hva = __gfn_to_hva_many(slot, gfn, NULL, false);
  1147. if (!kvm_is_error_hva(hva) && writable)
  1148. *writable = !memslot_is_readonly(slot);
  1149. return hva;
  1150. }
  1151. unsigned long gfn_to_hva_prot(struct kvm *kvm, gfn_t gfn, bool *writable)
  1152. {
  1153. struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
  1154. return gfn_to_hva_memslot_prot(slot, gfn, writable);
  1155. }
  1156. unsigned long kvm_vcpu_gfn_to_hva_prot(struct kvm_vcpu *vcpu, gfn_t gfn, bool *writable)
  1157. {
  1158. struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  1159. return gfn_to_hva_memslot_prot(slot, gfn, writable);
  1160. }
  1161. static inline int check_user_page_hwpoison(unsigned long addr)
  1162. {
  1163. int rc, flags = FOLL_HWPOISON | FOLL_WRITE;
  1164. rc = get_user_pages(addr, 1, flags, NULL, NULL);
  1165. return rc == -EHWPOISON;
  1166. }
  1167. /*
  1168. * The fast path to get the writable pfn which will be stored in @pfn,
  1169. * true indicates success, otherwise false is returned. It's also the
  1170. * only part that runs if we can are in atomic context.
  1171. */
  1172. static bool hva_to_pfn_fast(unsigned long addr, bool write_fault,
  1173. bool *writable, kvm_pfn_t *pfn)
  1174. {
  1175. struct page *page[1];
  1176. int npages;
  1177. /*
  1178. * Fast pin a writable pfn only if it is a write fault request
  1179. * or the caller allows to map a writable pfn for a read fault
  1180. * request.
  1181. */
  1182. if (!(write_fault || writable))
  1183. return false;
  1184. npages = __get_user_pages_fast(addr, 1, 1, page);
  1185. if (npages == 1) {
  1186. *pfn = page_to_pfn(page[0]);
  1187. if (writable)
  1188. *writable = true;
  1189. return true;
  1190. }
  1191. return false;
  1192. }
  1193. /*
  1194. * The slow path to get the pfn of the specified host virtual address,
  1195. * 1 indicates success, -errno is returned if error is detected.
  1196. */
  1197. static int hva_to_pfn_slow(unsigned long addr, bool *async, bool write_fault,
  1198. bool *writable, kvm_pfn_t *pfn)
  1199. {
  1200. unsigned int flags = FOLL_HWPOISON;
  1201. struct page *page;
  1202. int npages = 0;
  1203. might_sleep();
  1204. if (writable)
  1205. *writable = write_fault;
  1206. if (write_fault)
  1207. flags |= FOLL_WRITE;
  1208. if (async)
  1209. flags |= FOLL_NOWAIT;
  1210. npages = get_user_pages_unlocked(addr, 1, &page, flags);
  1211. if (npages != 1)
  1212. return npages;
  1213. /* map read fault as writable if possible */
  1214. if (unlikely(!write_fault) && writable) {
  1215. struct page *wpage;
  1216. if (__get_user_pages_fast(addr, 1, 1, &wpage) == 1) {
  1217. *writable = true;
  1218. put_page(page);
  1219. page = wpage;
  1220. }
  1221. }
  1222. *pfn = page_to_pfn(page);
  1223. return npages;
  1224. }
  1225. static bool vma_is_valid(struct vm_area_struct *vma, bool write_fault)
  1226. {
  1227. if (unlikely(!(vma->vm_flags & VM_READ)))
  1228. return false;
  1229. if (write_fault && (unlikely(!(vma->vm_flags & VM_WRITE))))
  1230. return false;
  1231. return true;
  1232. }
  1233. static int hva_to_pfn_remapped(struct vm_area_struct *vma,
  1234. unsigned long addr, bool *async,
  1235. bool write_fault, bool *writable,
  1236. kvm_pfn_t *p_pfn)
  1237. {
  1238. unsigned long pfn;
  1239. int r;
  1240. r = follow_pfn(vma, addr, &pfn);
  1241. if (r) {
  1242. /*
  1243. * get_user_pages fails for VM_IO and VM_PFNMAP vmas and does
  1244. * not call the fault handler, so do it here.
  1245. */
  1246. bool unlocked = false;
  1247. r = fixup_user_fault(current, current->mm, addr,
  1248. (write_fault ? FAULT_FLAG_WRITE : 0),
  1249. &unlocked);
  1250. if (unlocked)
  1251. return -EAGAIN;
  1252. if (r)
  1253. return r;
  1254. r = follow_pfn(vma, addr, &pfn);
  1255. if (r)
  1256. return r;
  1257. }
  1258. if (writable)
  1259. *writable = true;
  1260. /*
  1261. * Get a reference here because callers of *hva_to_pfn* and
  1262. * *gfn_to_pfn* ultimately call kvm_release_pfn_clean on the
  1263. * returned pfn. This is only needed if the VMA has VM_MIXEDMAP
  1264. * set, but the kvm_get_pfn/kvm_release_pfn_clean pair will
  1265. * simply do nothing for reserved pfns.
  1266. *
  1267. * Whoever called remap_pfn_range is also going to call e.g.
  1268. * unmap_mapping_range before the underlying pages are freed,
  1269. * causing a call to our MMU notifier.
  1270. */
  1271. kvm_get_pfn(pfn);
  1272. *p_pfn = pfn;
  1273. return 0;
  1274. }
  1275. /*
  1276. * Pin guest page in memory and return its pfn.
  1277. * @addr: host virtual address which maps memory to the guest
  1278. * @atomic: whether this function can sleep
  1279. * @async: whether this function need to wait IO complete if the
  1280. * host page is not in the memory
  1281. * @write_fault: whether we should get a writable host page
  1282. * @writable: whether it allows to map a writable host page for !@write_fault
  1283. *
  1284. * The function will map a writable host page for these two cases:
  1285. * 1): @write_fault = true
  1286. * 2): @write_fault = false && @writable, @writable will tell the caller
  1287. * whether the mapping is writable.
  1288. */
  1289. static kvm_pfn_t hva_to_pfn(unsigned long addr, bool atomic, bool *async,
  1290. bool write_fault, bool *writable)
  1291. {
  1292. struct vm_area_struct *vma;
  1293. kvm_pfn_t pfn = 0;
  1294. int npages, r;
  1295. /* we can do it either atomically or asynchronously, not both */
  1296. BUG_ON(atomic && async);
  1297. if (hva_to_pfn_fast(addr, write_fault, writable, &pfn))
  1298. return pfn;
  1299. if (atomic)
  1300. return KVM_PFN_ERR_FAULT;
  1301. npages = hva_to_pfn_slow(addr, async, write_fault, writable, &pfn);
  1302. if (npages == 1)
  1303. return pfn;
  1304. down_read(&current->mm->mmap_sem);
  1305. if (npages == -EHWPOISON ||
  1306. (!async && check_user_page_hwpoison(addr))) {
  1307. pfn = KVM_PFN_ERR_HWPOISON;
  1308. goto exit;
  1309. }
  1310. retry:
  1311. vma = find_vma_intersection(current->mm, addr, addr + 1);
  1312. if (vma == NULL)
  1313. pfn = KVM_PFN_ERR_FAULT;
  1314. else if (vma->vm_flags & (VM_IO | VM_PFNMAP)) {
  1315. r = hva_to_pfn_remapped(vma, addr, async, write_fault, writable, &pfn);
  1316. if (r == -EAGAIN)
  1317. goto retry;
  1318. if (r < 0)
  1319. pfn = KVM_PFN_ERR_FAULT;
  1320. } else {
  1321. if (async && vma_is_valid(vma, write_fault))
  1322. *async = true;
  1323. pfn = KVM_PFN_ERR_FAULT;
  1324. }
  1325. exit:
  1326. up_read(&current->mm->mmap_sem);
  1327. return pfn;
  1328. }
  1329. kvm_pfn_t __gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn,
  1330. bool atomic, bool *async, bool write_fault,
  1331. bool *writable)
  1332. {
  1333. unsigned long addr = __gfn_to_hva_many(slot, gfn, NULL, write_fault);
  1334. if (addr == KVM_HVA_ERR_RO_BAD) {
  1335. if (writable)
  1336. *writable = false;
  1337. return KVM_PFN_ERR_RO_FAULT;
  1338. }
  1339. if (kvm_is_error_hva(addr)) {
  1340. if (writable)
  1341. *writable = false;
  1342. return KVM_PFN_NOSLOT;
  1343. }
  1344. /* Do not map writable pfn in the readonly memslot. */
  1345. if (writable && memslot_is_readonly(slot)) {
  1346. *writable = false;
  1347. writable = NULL;
  1348. }
  1349. return hva_to_pfn(addr, atomic, async, write_fault,
  1350. writable);
  1351. }
  1352. EXPORT_SYMBOL_GPL(__gfn_to_pfn_memslot);
  1353. kvm_pfn_t gfn_to_pfn_prot(struct kvm *kvm, gfn_t gfn, bool write_fault,
  1354. bool *writable)
  1355. {
  1356. return __gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn, false, NULL,
  1357. write_fault, writable);
  1358. }
  1359. EXPORT_SYMBOL_GPL(gfn_to_pfn_prot);
  1360. kvm_pfn_t gfn_to_pfn_memslot(struct kvm_memory_slot *slot, gfn_t gfn)
  1361. {
  1362. return __gfn_to_pfn_memslot(slot, gfn, false, NULL, true, NULL);
  1363. }
  1364. EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot);
  1365. kvm_pfn_t gfn_to_pfn_memslot_atomic(struct kvm_memory_slot *slot, gfn_t gfn)
  1366. {
  1367. return __gfn_to_pfn_memslot(slot, gfn, true, NULL, true, NULL);
  1368. }
  1369. EXPORT_SYMBOL_GPL(gfn_to_pfn_memslot_atomic);
  1370. kvm_pfn_t gfn_to_pfn_atomic(struct kvm *kvm, gfn_t gfn)
  1371. {
  1372. return gfn_to_pfn_memslot_atomic(gfn_to_memslot(kvm, gfn), gfn);
  1373. }
  1374. EXPORT_SYMBOL_GPL(gfn_to_pfn_atomic);
  1375. kvm_pfn_t kvm_vcpu_gfn_to_pfn_atomic(struct kvm_vcpu *vcpu, gfn_t gfn)
  1376. {
  1377. return gfn_to_pfn_memslot_atomic(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
  1378. }
  1379. EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn_atomic);
  1380. kvm_pfn_t gfn_to_pfn(struct kvm *kvm, gfn_t gfn)
  1381. {
  1382. return gfn_to_pfn_memslot(gfn_to_memslot(kvm, gfn), gfn);
  1383. }
  1384. EXPORT_SYMBOL_GPL(gfn_to_pfn);
  1385. kvm_pfn_t kvm_vcpu_gfn_to_pfn(struct kvm_vcpu *vcpu, gfn_t gfn)
  1386. {
  1387. return gfn_to_pfn_memslot(kvm_vcpu_gfn_to_memslot(vcpu, gfn), gfn);
  1388. }
  1389. EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_pfn);
  1390. int gfn_to_page_many_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
  1391. struct page **pages, int nr_pages)
  1392. {
  1393. unsigned long addr;
  1394. gfn_t entry = 0;
  1395. addr = gfn_to_hva_many(slot, gfn, &entry);
  1396. if (kvm_is_error_hva(addr))
  1397. return -1;
  1398. if (entry < nr_pages)
  1399. return 0;
  1400. return __get_user_pages_fast(addr, nr_pages, 1, pages);
  1401. }
  1402. EXPORT_SYMBOL_GPL(gfn_to_page_many_atomic);
  1403. static struct page *kvm_pfn_to_page(kvm_pfn_t pfn)
  1404. {
  1405. if (is_error_noslot_pfn(pfn))
  1406. return KVM_ERR_PTR_BAD_PAGE;
  1407. if (kvm_is_reserved_pfn(pfn)) {
  1408. WARN_ON(1);
  1409. return KVM_ERR_PTR_BAD_PAGE;
  1410. }
  1411. return pfn_to_page(pfn);
  1412. }
  1413. struct page *gfn_to_page(struct kvm *kvm, gfn_t gfn)
  1414. {
  1415. kvm_pfn_t pfn;
  1416. pfn = gfn_to_pfn(kvm, gfn);
  1417. return kvm_pfn_to_page(pfn);
  1418. }
  1419. EXPORT_SYMBOL_GPL(gfn_to_page);
  1420. void kvm_release_pfn(kvm_pfn_t pfn, bool dirty, struct gfn_to_pfn_cache *cache)
  1421. {
  1422. if (pfn == 0)
  1423. return;
  1424. if (cache)
  1425. cache->pfn = cache->gfn = 0;
  1426. if (dirty)
  1427. kvm_release_pfn_dirty(pfn);
  1428. else
  1429. kvm_release_pfn_clean(pfn);
  1430. }
  1431. static void kvm_cache_gfn_to_pfn(struct kvm_memory_slot *slot, gfn_t gfn,
  1432. struct gfn_to_pfn_cache *cache, u64 gen)
  1433. {
  1434. kvm_release_pfn(cache->pfn, cache->dirty, cache);
  1435. cache->pfn = gfn_to_pfn_memslot(slot, gfn);
  1436. cache->gfn = gfn;
  1437. cache->dirty = false;
  1438. cache->generation = gen;
  1439. }
  1440. static int __kvm_map_gfn(struct kvm_memslots *slots, gfn_t gfn,
  1441. struct kvm_host_map *map,
  1442. struct gfn_to_pfn_cache *cache,
  1443. bool atomic)
  1444. {
  1445. kvm_pfn_t pfn;
  1446. void *hva = NULL;
  1447. struct page *page = KVM_UNMAPPED_PAGE;
  1448. struct kvm_memory_slot *slot = __gfn_to_memslot(slots, gfn);
  1449. u64 gen = slots->generation;
  1450. if (!map)
  1451. return -EINVAL;
  1452. if (cache) {
  1453. if (!cache->pfn || cache->gfn != gfn ||
  1454. cache->generation != gen) {
  1455. if (atomic)
  1456. return -EAGAIN;
  1457. kvm_cache_gfn_to_pfn(slot, gfn, cache, gen);
  1458. }
  1459. pfn = cache->pfn;
  1460. } else {
  1461. if (atomic)
  1462. return -EAGAIN;
  1463. pfn = gfn_to_pfn_memslot(slot, gfn);
  1464. }
  1465. if (is_error_noslot_pfn(pfn))
  1466. return -EINVAL;
  1467. if (pfn_valid(pfn)) {
  1468. page = pfn_to_page(pfn);
  1469. if (atomic)
  1470. hva = kmap_atomic(page);
  1471. else
  1472. hva = kmap(page);
  1473. #ifdef CONFIG_HAS_IOMEM
  1474. } else if (!atomic) {
  1475. hva = memremap(pfn_to_hpa(pfn), PAGE_SIZE, MEMREMAP_WB);
  1476. } else {
  1477. return -EINVAL;
  1478. #endif
  1479. }
  1480. if (!hva)
  1481. return -EFAULT;
  1482. map->page = page;
  1483. map->hva = hva;
  1484. map->pfn = pfn;
  1485. map->gfn = gfn;
  1486. return 0;
  1487. }
  1488. int kvm_map_gfn(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map,
  1489. struct gfn_to_pfn_cache *cache, bool atomic)
  1490. {
  1491. return __kvm_map_gfn(kvm_memslots(vcpu->kvm), gfn, map,
  1492. cache, atomic);
  1493. }
  1494. EXPORT_SYMBOL_GPL(kvm_map_gfn);
  1495. int kvm_vcpu_map(struct kvm_vcpu *vcpu, gfn_t gfn, struct kvm_host_map *map)
  1496. {
  1497. return __kvm_map_gfn(kvm_vcpu_memslots(vcpu), gfn, map,
  1498. NULL, false);
  1499. }
  1500. EXPORT_SYMBOL_GPL(kvm_vcpu_map);
  1501. static void __kvm_unmap_gfn(struct kvm_memory_slot *memslot,
  1502. struct kvm_host_map *map,
  1503. struct gfn_to_pfn_cache *cache,
  1504. bool dirty, bool atomic)
  1505. {
  1506. if (!map)
  1507. return;
  1508. if (!map->hva)
  1509. return;
  1510. if (map->page != KVM_UNMAPPED_PAGE) {
  1511. if (atomic)
  1512. kunmap_atomic(map->hva);
  1513. else
  1514. kunmap(map->page);
  1515. }
  1516. #ifdef CONFIG_HAS_IOMEM
  1517. else if (!atomic)
  1518. memunmap(map->hva);
  1519. else
  1520. WARN_ONCE(1, "Unexpected unmapping in atomic context");
  1521. #endif
  1522. if (dirty)
  1523. mark_page_dirty_in_slot(memslot, map->gfn);
  1524. if (cache)
  1525. cache->dirty |= dirty;
  1526. else
  1527. kvm_release_pfn(map->pfn, dirty, NULL);
  1528. map->hva = NULL;
  1529. map->page = NULL;
  1530. }
  1531. int kvm_unmap_gfn(struct kvm_vcpu *vcpu, struct kvm_host_map *map,
  1532. struct gfn_to_pfn_cache *cache, bool dirty, bool atomic)
  1533. {
  1534. __kvm_unmap_gfn(gfn_to_memslot(vcpu->kvm, map->gfn), map,
  1535. cache, dirty, atomic);
  1536. return 0;
  1537. }
  1538. EXPORT_SYMBOL_GPL(kvm_unmap_gfn);
  1539. void kvm_vcpu_unmap(struct kvm_vcpu *vcpu, struct kvm_host_map *map, bool dirty)
  1540. {
  1541. __kvm_unmap_gfn(kvm_vcpu_gfn_to_memslot(vcpu, map->gfn), map, NULL,
  1542. dirty, false);
  1543. }
  1544. EXPORT_SYMBOL_GPL(kvm_vcpu_unmap);
  1545. struct page *kvm_vcpu_gfn_to_page(struct kvm_vcpu *vcpu, gfn_t gfn)
  1546. {
  1547. kvm_pfn_t pfn;
  1548. pfn = kvm_vcpu_gfn_to_pfn(vcpu, gfn);
  1549. return kvm_pfn_to_page(pfn);
  1550. }
  1551. EXPORT_SYMBOL_GPL(kvm_vcpu_gfn_to_page);
  1552. void kvm_release_page_clean(struct page *page)
  1553. {
  1554. WARN_ON(is_error_page(page));
  1555. kvm_release_pfn_clean(page_to_pfn(page));
  1556. }
  1557. EXPORT_SYMBOL_GPL(kvm_release_page_clean);
  1558. void kvm_release_pfn_clean(kvm_pfn_t pfn)
  1559. {
  1560. if (!is_error_noslot_pfn(pfn) && !kvm_is_reserved_pfn(pfn))
  1561. put_page(pfn_to_page(pfn));
  1562. }
  1563. EXPORT_SYMBOL_GPL(kvm_release_pfn_clean);
  1564. void kvm_release_page_dirty(struct page *page)
  1565. {
  1566. WARN_ON(is_error_page(page));
  1567. kvm_release_pfn_dirty(page_to_pfn(page));
  1568. }
  1569. EXPORT_SYMBOL_GPL(kvm_release_page_dirty);
  1570. void kvm_release_pfn_dirty(kvm_pfn_t pfn)
  1571. {
  1572. kvm_set_pfn_dirty(pfn);
  1573. kvm_release_pfn_clean(pfn);
  1574. }
  1575. EXPORT_SYMBOL_GPL(kvm_release_pfn_dirty);
  1576. void kvm_set_pfn_dirty(kvm_pfn_t pfn)
  1577. {
  1578. if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn)) {
  1579. struct page *page = pfn_to_page(pfn);
  1580. if (!PageReserved(page))
  1581. SetPageDirty(page);
  1582. }
  1583. }
  1584. EXPORT_SYMBOL_GPL(kvm_set_pfn_dirty);
  1585. void kvm_set_pfn_accessed(kvm_pfn_t pfn)
  1586. {
  1587. if (!kvm_is_reserved_pfn(pfn) && !kvm_is_zone_device_pfn(pfn))
  1588. mark_page_accessed(pfn_to_page(pfn));
  1589. }
  1590. EXPORT_SYMBOL_GPL(kvm_set_pfn_accessed);
  1591. void kvm_get_pfn(kvm_pfn_t pfn)
  1592. {
  1593. if (!kvm_is_reserved_pfn(pfn))
  1594. get_page(pfn_to_page(pfn));
  1595. }
  1596. EXPORT_SYMBOL_GPL(kvm_get_pfn);
  1597. static int next_segment(unsigned long len, int offset)
  1598. {
  1599. if (len > PAGE_SIZE - offset)
  1600. return PAGE_SIZE - offset;
  1601. else
  1602. return len;
  1603. }
  1604. static int __kvm_read_guest_page(struct kvm_memory_slot *slot, gfn_t gfn,
  1605. void *data, int offset, int len)
  1606. {
  1607. int r;
  1608. unsigned long addr;
  1609. addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
  1610. if (kvm_is_error_hva(addr))
  1611. return -EFAULT;
  1612. r = __copy_from_user(data, (void __user *)addr + offset, len);
  1613. if (r)
  1614. return -EFAULT;
  1615. return 0;
  1616. }
  1617. int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset,
  1618. int len)
  1619. {
  1620. struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
  1621. return __kvm_read_guest_page(slot, gfn, data, offset, len);
  1622. }
  1623. EXPORT_SYMBOL_GPL(kvm_read_guest_page);
  1624. int kvm_vcpu_read_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn, void *data,
  1625. int offset, int len)
  1626. {
  1627. struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  1628. return __kvm_read_guest_page(slot, gfn, data, offset, len);
  1629. }
  1630. EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_page);
  1631. int kvm_read_guest(struct kvm *kvm, gpa_t gpa, void *data, unsigned long len)
  1632. {
  1633. gfn_t gfn = gpa >> PAGE_SHIFT;
  1634. int seg;
  1635. int offset = offset_in_page(gpa);
  1636. int ret;
  1637. while ((seg = next_segment(len, offset)) != 0) {
  1638. ret = kvm_read_guest_page(kvm, gfn, data, offset, seg);
  1639. if (ret < 0)
  1640. return ret;
  1641. offset = 0;
  1642. len -= seg;
  1643. data += seg;
  1644. ++gfn;
  1645. }
  1646. return 0;
  1647. }
  1648. EXPORT_SYMBOL_GPL(kvm_read_guest);
  1649. int kvm_vcpu_read_guest(struct kvm_vcpu *vcpu, gpa_t gpa, void *data, unsigned long len)
  1650. {
  1651. gfn_t gfn = gpa >> PAGE_SHIFT;
  1652. int seg;
  1653. int offset = offset_in_page(gpa);
  1654. int ret;
  1655. while ((seg = next_segment(len, offset)) != 0) {
  1656. ret = kvm_vcpu_read_guest_page(vcpu, gfn, data, offset, seg);
  1657. if (ret < 0)
  1658. return ret;
  1659. offset = 0;
  1660. len -= seg;
  1661. data += seg;
  1662. ++gfn;
  1663. }
  1664. return 0;
  1665. }
  1666. EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest);
  1667. static int __kvm_read_guest_atomic(struct kvm_memory_slot *slot, gfn_t gfn,
  1668. void *data, int offset, unsigned long len)
  1669. {
  1670. int r;
  1671. unsigned long addr;
  1672. addr = gfn_to_hva_memslot_prot(slot, gfn, NULL);
  1673. if (kvm_is_error_hva(addr))
  1674. return -EFAULT;
  1675. pagefault_disable();
  1676. r = __copy_from_user_inatomic(data, (void __user *)addr + offset, len);
  1677. pagefault_enable();
  1678. if (r)
  1679. return -EFAULT;
  1680. return 0;
  1681. }
  1682. int kvm_read_guest_atomic(struct kvm *kvm, gpa_t gpa, void *data,
  1683. unsigned long len)
  1684. {
  1685. gfn_t gfn = gpa >> PAGE_SHIFT;
  1686. struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
  1687. int offset = offset_in_page(gpa);
  1688. return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
  1689. }
  1690. EXPORT_SYMBOL_GPL(kvm_read_guest_atomic);
  1691. int kvm_vcpu_read_guest_atomic(struct kvm_vcpu *vcpu, gpa_t gpa,
  1692. void *data, unsigned long len)
  1693. {
  1694. gfn_t gfn = gpa >> PAGE_SHIFT;
  1695. struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  1696. int offset = offset_in_page(gpa);
  1697. return __kvm_read_guest_atomic(slot, gfn, data, offset, len);
  1698. }
  1699. EXPORT_SYMBOL_GPL(kvm_vcpu_read_guest_atomic);
  1700. static int __kvm_write_guest_page(struct kvm_memory_slot *memslot, gfn_t gfn,
  1701. const void *data, int offset, int len)
  1702. {
  1703. int r;
  1704. unsigned long addr;
  1705. addr = gfn_to_hva_memslot(memslot, gfn);
  1706. if (kvm_is_error_hva(addr))
  1707. return -EFAULT;
  1708. r = __copy_to_user((void __user *)addr + offset, data, len);
  1709. if (r)
  1710. return -EFAULT;
  1711. mark_page_dirty_in_slot(memslot, gfn);
  1712. return 0;
  1713. }
  1714. int kvm_write_guest_page(struct kvm *kvm, gfn_t gfn,
  1715. const void *data, int offset, int len)
  1716. {
  1717. struct kvm_memory_slot *slot = gfn_to_memslot(kvm, gfn);
  1718. return __kvm_write_guest_page(slot, gfn, data, offset, len);
  1719. }
  1720. EXPORT_SYMBOL_GPL(kvm_write_guest_page);
  1721. int kvm_vcpu_write_guest_page(struct kvm_vcpu *vcpu, gfn_t gfn,
  1722. const void *data, int offset, int len)
  1723. {
  1724. struct kvm_memory_slot *slot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  1725. return __kvm_write_guest_page(slot, gfn, data, offset, len);
  1726. }
  1727. EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest_page);
  1728. int kvm_write_guest(struct kvm *kvm, gpa_t gpa, const void *data,
  1729. unsigned long len)
  1730. {
  1731. gfn_t gfn = gpa >> PAGE_SHIFT;
  1732. int seg;
  1733. int offset = offset_in_page(gpa);
  1734. int ret;
  1735. while ((seg = next_segment(len, offset)) != 0) {
  1736. ret = kvm_write_guest_page(kvm, gfn, data, offset, seg);
  1737. if (ret < 0)
  1738. return ret;
  1739. offset = 0;
  1740. len -= seg;
  1741. data += seg;
  1742. ++gfn;
  1743. }
  1744. return 0;
  1745. }
  1746. EXPORT_SYMBOL_GPL(kvm_write_guest);
  1747. int kvm_vcpu_write_guest(struct kvm_vcpu *vcpu, gpa_t gpa, const void *data,
  1748. unsigned long len)
  1749. {
  1750. gfn_t gfn = gpa >> PAGE_SHIFT;
  1751. int seg;
  1752. int offset = offset_in_page(gpa);
  1753. int ret;
  1754. while ((seg = next_segment(len, offset)) != 0) {
  1755. ret = kvm_vcpu_write_guest_page(vcpu, gfn, data, offset, seg);
  1756. if (ret < 0)
  1757. return ret;
  1758. offset = 0;
  1759. len -= seg;
  1760. data += seg;
  1761. ++gfn;
  1762. }
  1763. return 0;
  1764. }
  1765. EXPORT_SYMBOL_GPL(kvm_vcpu_write_guest);
  1766. static int __kvm_gfn_to_hva_cache_init(struct kvm_memslots *slots,
  1767. struct gfn_to_hva_cache *ghc,
  1768. gpa_t gpa, unsigned long len)
  1769. {
  1770. int offset = offset_in_page(gpa);
  1771. gfn_t start_gfn = gpa >> PAGE_SHIFT;
  1772. gfn_t end_gfn = (gpa + len - 1) >> PAGE_SHIFT;
  1773. gfn_t nr_pages_needed = end_gfn - start_gfn + 1;
  1774. gfn_t nr_pages_avail;
  1775. ghc->gpa = gpa;
  1776. ghc->generation = slots->generation;
  1777. ghc->len = len;
  1778. ghc->memslot = __gfn_to_memslot(slots, start_gfn);
  1779. ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn, NULL);
  1780. if (!kvm_is_error_hva(ghc->hva) && nr_pages_needed <= 1) {
  1781. ghc->hva += offset;
  1782. } else {
  1783. /*
  1784. * If the requested region crosses two memslots, we still
  1785. * verify that the entire region is valid here.
  1786. */
  1787. while (start_gfn <= end_gfn) {
  1788. nr_pages_avail = 0;
  1789. ghc->memslot = __gfn_to_memslot(slots, start_gfn);
  1790. ghc->hva = gfn_to_hva_many(ghc->memslot, start_gfn,
  1791. &nr_pages_avail);
  1792. if (kvm_is_error_hva(ghc->hva))
  1793. return -EFAULT;
  1794. start_gfn += nr_pages_avail;
  1795. }
  1796. /* Use the slow path for cross page reads and writes. */
  1797. ghc->memslot = NULL;
  1798. }
  1799. return 0;
  1800. }
  1801. int kvm_gfn_to_hva_cache_init(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
  1802. gpa_t gpa, unsigned long len)
  1803. {
  1804. struct kvm_memslots *slots = kvm_memslots(kvm);
  1805. return __kvm_gfn_to_hva_cache_init(slots, ghc, gpa, len);
  1806. }
  1807. EXPORT_SYMBOL_GPL(kvm_gfn_to_hva_cache_init);
  1808. int kvm_write_guest_offset_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
  1809. void *data, unsigned int offset,
  1810. unsigned long len)
  1811. {
  1812. struct kvm_memslots *slots = kvm_memslots(kvm);
  1813. int r;
  1814. gpa_t gpa = ghc->gpa + offset;
  1815. BUG_ON(len + offset > ghc->len);
  1816. if (slots->generation != ghc->generation)
  1817. __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
  1818. if (kvm_is_error_hva(ghc->hva))
  1819. return -EFAULT;
  1820. if (unlikely(!ghc->memslot))
  1821. return kvm_write_guest(kvm, gpa, data, len);
  1822. r = __copy_to_user((void __user *)ghc->hva + offset, data, len);
  1823. if (r)
  1824. return -EFAULT;
  1825. mark_page_dirty_in_slot(ghc->memslot, gpa >> PAGE_SHIFT);
  1826. return 0;
  1827. }
  1828. EXPORT_SYMBOL_GPL(kvm_write_guest_offset_cached);
  1829. int kvm_write_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
  1830. void *data, unsigned long len)
  1831. {
  1832. return kvm_write_guest_offset_cached(kvm, ghc, data, 0, len);
  1833. }
  1834. EXPORT_SYMBOL_GPL(kvm_write_guest_cached);
  1835. int kvm_read_guest_cached(struct kvm *kvm, struct gfn_to_hva_cache *ghc,
  1836. void *data, unsigned long len)
  1837. {
  1838. struct kvm_memslots *slots = kvm_memslots(kvm);
  1839. int r;
  1840. BUG_ON(len > ghc->len);
  1841. if (slots->generation != ghc->generation)
  1842. __kvm_gfn_to_hva_cache_init(slots, ghc, ghc->gpa, ghc->len);
  1843. if (kvm_is_error_hva(ghc->hva))
  1844. return -EFAULT;
  1845. if (unlikely(!ghc->memslot))
  1846. return kvm_read_guest(kvm, ghc->gpa, data, len);
  1847. r = __copy_from_user(data, (void __user *)ghc->hva, len);
  1848. if (r)
  1849. return -EFAULT;
  1850. return 0;
  1851. }
  1852. EXPORT_SYMBOL_GPL(kvm_read_guest_cached);
  1853. int kvm_clear_guest_page(struct kvm *kvm, gfn_t gfn, int offset, int len)
  1854. {
  1855. const void *zero_page = (const void *) __va(page_to_phys(ZERO_PAGE(0)));
  1856. return kvm_write_guest_page(kvm, gfn, zero_page, offset, len);
  1857. }
  1858. EXPORT_SYMBOL_GPL(kvm_clear_guest_page);
  1859. int kvm_clear_guest(struct kvm *kvm, gpa_t gpa, unsigned long len)
  1860. {
  1861. gfn_t gfn = gpa >> PAGE_SHIFT;
  1862. int seg;
  1863. int offset = offset_in_page(gpa);
  1864. int ret;
  1865. while ((seg = next_segment(len, offset)) != 0) {
  1866. ret = kvm_clear_guest_page(kvm, gfn, offset, seg);
  1867. if (ret < 0)
  1868. return ret;
  1869. offset = 0;
  1870. len -= seg;
  1871. ++gfn;
  1872. }
  1873. return 0;
  1874. }
  1875. EXPORT_SYMBOL_GPL(kvm_clear_guest);
  1876. static void mark_page_dirty_in_slot(struct kvm_memory_slot *memslot,
  1877. gfn_t gfn)
  1878. {
  1879. if (memslot && memslot->dirty_bitmap) {
  1880. unsigned long rel_gfn = gfn - memslot->base_gfn;
  1881. set_bit_le(rel_gfn, memslot->dirty_bitmap);
  1882. }
  1883. }
  1884. void mark_page_dirty(struct kvm *kvm, gfn_t gfn)
  1885. {
  1886. struct kvm_memory_slot *memslot;
  1887. memslot = gfn_to_memslot(kvm, gfn);
  1888. mark_page_dirty_in_slot(memslot, gfn);
  1889. }
  1890. EXPORT_SYMBOL_GPL(mark_page_dirty);
  1891. void kvm_vcpu_mark_page_dirty(struct kvm_vcpu *vcpu, gfn_t gfn)
  1892. {
  1893. struct kvm_memory_slot *memslot;
  1894. memslot = kvm_vcpu_gfn_to_memslot(vcpu, gfn);
  1895. mark_page_dirty_in_slot(memslot, gfn);
  1896. }
  1897. EXPORT_SYMBOL_GPL(kvm_vcpu_mark_page_dirty);
  1898. void kvm_sigset_activate(struct kvm_vcpu *vcpu)
  1899. {
  1900. if (!vcpu->sigset_active)
  1901. return;
  1902. /*
  1903. * This does a lockless modification of ->real_blocked, which is fine
  1904. * because, only current can change ->real_blocked and all readers of
  1905. * ->real_blocked don't care as long ->real_blocked is always a subset
  1906. * of ->blocked.
  1907. */
  1908. sigprocmask(SIG_SETMASK, &vcpu->sigset, &current->real_blocked);
  1909. }
  1910. void kvm_sigset_deactivate(struct kvm_vcpu *vcpu)
  1911. {
  1912. if (!vcpu->sigset_active)
  1913. return;
  1914. sigprocmask(SIG_SETMASK, &current->real_blocked, NULL);
  1915. sigemptyset(&current->real_blocked);
  1916. }
  1917. static void grow_halt_poll_ns(struct kvm_vcpu *vcpu)
  1918. {
  1919. unsigned int old, val, grow;
  1920. old = val = vcpu->halt_poll_ns;
  1921. grow = READ_ONCE(halt_poll_ns_grow);
  1922. /* 10us base */
  1923. if (val == 0 && grow)
  1924. val = 10000;
  1925. else
  1926. val *= grow;
  1927. if (val > halt_poll_ns)
  1928. val = halt_poll_ns;
  1929. vcpu->halt_poll_ns = val;
  1930. trace_kvm_halt_poll_ns_grow(vcpu->vcpu_id, val, old);
  1931. }
  1932. static void shrink_halt_poll_ns(struct kvm_vcpu *vcpu)
  1933. {
  1934. unsigned int old, val, shrink;
  1935. old = val = vcpu->halt_poll_ns;
  1936. shrink = READ_ONCE(halt_poll_ns_shrink);
  1937. if (shrink == 0)
  1938. val = 0;
  1939. else
  1940. val /= shrink;
  1941. vcpu->halt_poll_ns = val;
  1942. trace_kvm_halt_poll_ns_shrink(vcpu->vcpu_id, val, old);
  1943. }
  1944. static int kvm_vcpu_check_block(struct kvm_vcpu *vcpu)
  1945. {
  1946. int ret = -EINTR;
  1947. int idx = srcu_read_lock(&vcpu->kvm->srcu);
  1948. if (kvm_arch_vcpu_runnable(vcpu)) {
  1949. kvm_make_request(KVM_REQ_UNHALT, vcpu);
  1950. goto out;
  1951. }
  1952. if (kvm_cpu_has_pending_timer(vcpu))
  1953. goto out;
  1954. if (signal_pending(current))
  1955. goto out;
  1956. ret = 0;
  1957. out:
  1958. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  1959. return ret;
  1960. }
  1961. /*
  1962. * The vCPU has executed a HLT instruction with in-kernel mode enabled.
  1963. */
  1964. void kvm_vcpu_block(struct kvm_vcpu *vcpu)
  1965. {
  1966. ktime_t start, cur;
  1967. DECLARE_SWAITQUEUE(wait);
  1968. bool waited = false;
  1969. u64 block_ns;
  1970. start = cur = ktime_get();
  1971. if (vcpu->halt_poll_ns) {
  1972. ktime_t stop = ktime_add_ns(ktime_get(), vcpu->halt_poll_ns);
  1973. ++vcpu->stat.halt_attempted_poll;
  1974. do {
  1975. /*
  1976. * This sets KVM_REQ_UNHALT if an interrupt
  1977. * arrives.
  1978. */
  1979. if (kvm_vcpu_check_block(vcpu) < 0) {
  1980. ++vcpu->stat.halt_successful_poll;
  1981. if (!vcpu_valid_wakeup(vcpu))
  1982. ++vcpu->stat.halt_poll_invalid;
  1983. goto out;
  1984. }
  1985. cur = ktime_get();
  1986. } while (single_task_running() && ktime_before(cur, stop));
  1987. }
  1988. kvm_arch_vcpu_blocking(vcpu);
  1989. for (;;) {
  1990. prepare_to_swait_exclusive(&vcpu->wq, &wait, TASK_INTERRUPTIBLE);
  1991. if (kvm_vcpu_check_block(vcpu) < 0)
  1992. break;
  1993. waited = true;
  1994. schedule();
  1995. }
  1996. finish_swait(&vcpu->wq, &wait);
  1997. cur = ktime_get();
  1998. kvm_arch_vcpu_unblocking(vcpu);
  1999. out:
  2000. block_ns = ktime_to_ns(cur) - ktime_to_ns(start);
  2001. if (!vcpu_valid_wakeup(vcpu))
  2002. shrink_halt_poll_ns(vcpu);
  2003. else if (halt_poll_ns) {
  2004. if (block_ns <= vcpu->halt_poll_ns)
  2005. ;
  2006. /* we had a long block, shrink polling */
  2007. else if (vcpu->halt_poll_ns && block_ns > halt_poll_ns)
  2008. shrink_halt_poll_ns(vcpu);
  2009. /* we had a short halt and our poll time is too small */
  2010. else if (vcpu->halt_poll_ns < halt_poll_ns &&
  2011. block_ns < halt_poll_ns)
  2012. grow_halt_poll_ns(vcpu);
  2013. } else
  2014. vcpu->halt_poll_ns = 0;
  2015. trace_kvm_vcpu_wakeup(block_ns, waited, vcpu_valid_wakeup(vcpu));
  2016. kvm_arch_vcpu_block_finish(vcpu);
  2017. }
  2018. EXPORT_SYMBOL_GPL(kvm_vcpu_block);
  2019. bool kvm_vcpu_wake_up(struct kvm_vcpu *vcpu)
  2020. {
  2021. struct swait_queue_head *wqp;
  2022. wqp = kvm_arch_vcpu_wq(vcpu);
  2023. if (swq_has_sleeper(wqp)) {
  2024. swake_up_one(wqp);
  2025. ++vcpu->stat.halt_wakeup;
  2026. return true;
  2027. }
  2028. return false;
  2029. }
  2030. EXPORT_SYMBOL_GPL(kvm_vcpu_wake_up);
  2031. #ifndef CONFIG_S390
  2032. /*
  2033. * Kick a sleeping VCPU, or a guest VCPU in guest mode, into host kernel mode.
  2034. */
  2035. void kvm_vcpu_kick(struct kvm_vcpu *vcpu)
  2036. {
  2037. int me;
  2038. int cpu = vcpu->cpu;
  2039. if (kvm_vcpu_wake_up(vcpu))
  2040. return;
  2041. me = get_cpu();
  2042. if (cpu != me && (unsigned)cpu < nr_cpu_ids && cpu_online(cpu))
  2043. if (kvm_arch_vcpu_should_kick(vcpu))
  2044. smp_send_reschedule(cpu);
  2045. put_cpu();
  2046. }
  2047. EXPORT_SYMBOL_GPL(kvm_vcpu_kick);
  2048. #endif /* !CONFIG_S390 */
  2049. int kvm_vcpu_yield_to(struct kvm_vcpu *target)
  2050. {
  2051. struct pid *pid;
  2052. struct task_struct *task = NULL;
  2053. int ret = 0;
  2054. rcu_read_lock();
  2055. pid = rcu_dereference(target->pid);
  2056. if (pid)
  2057. task = get_pid_task(pid, PIDTYPE_PID);
  2058. rcu_read_unlock();
  2059. if (!task)
  2060. return ret;
  2061. ret = yield_to(task, 1);
  2062. put_task_struct(task);
  2063. return ret;
  2064. }
  2065. EXPORT_SYMBOL_GPL(kvm_vcpu_yield_to);
  2066. /*
  2067. * Helper that checks whether a VCPU is eligible for directed yield.
  2068. * Most eligible candidate to yield is decided by following heuristics:
  2069. *
  2070. * (a) VCPU which has not done pl-exit or cpu relax intercepted recently
  2071. * (preempted lock holder), indicated by @in_spin_loop.
  2072. * Set at the beiginning and cleared at the end of interception/PLE handler.
  2073. *
  2074. * (b) VCPU which has done pl-exit/ cpu relax intercepted but did not get
  2075. * chance last time (mostly it has become eligible now since we have probably
  2076. * yielded to lockholder in last iteration. This is done by toggling
  2077. * @dy_eligible each time a VCPU checked for eligibility.)
  2078. *
  2079. * Yielding to a recently pl-exited/cpu relax intercepted VCPU before yielding
  2080. * to preempted lock-holder could result in wrong VCPU selection and CPU
  2081. * burning. Giving priority for a potential lock-holder increases lock
  2082. * progress.
  2083. *
  2084. * Since algorithm is based on heuristics, accessing another VCPU data without
  2085. * locking does not harm. It may result in trying to yield to same VCPU, fail
  2086. * and continue with next VCPU and so on.
  2087. */
  2088. static bool kvm_vcpu_eligible_for_directed_yield(struct kvm_vcpu *vcpu)
  2089. {
  2090. #ifdef CONFIG_HAVE_KVM_CPU_RELAX_INTERCEPT
  2091. bool eligible;
  2092. eligible = !vcpu->spin_loop.in_spin_loop ||
  2093. vcpu->spin_loop.dy_eligible;
  2094. if (vcpu->spin_loop.in_spin_loop)
  2095. kvm_vcpu_set_dy_eligible(vcpu, !vcpu->spin_loop.dy_eligible);
  2096. return eligible;
  2097. #else
  2098. return true;
  2099. #endif
  2100. }
  2101. /*
  2102. * Unlike kvm_arch_vcpu_runnable, this function is called outside
  2103. * a vcpu_load/vcpu_put pair. However, for most architectures
  2104. * kvm_arch_vcpu_runnable does not require vcpu_load.
  2105. */
  2106. bool __weak kvm_arch_dy_runnable(struct kvm_vcpu *vcpu)
  2107. {
  2108. return kvm_arch_vcpu_runnable(vcpu);
  2109. }
  2110. static bool vcpu_dy_runnable(struct kvm_vcpu *vcpu)
  2111. {
  2112. if (kvm_arch_dy_runnable(vcpu))
  2113. return true;
  2114. #ifdef CONFIG_KVM_ASYNC_PF
  2115. if (!list_empty_careful(&vcpu->async_pf.done))
  2116. return true;
  2117. #endif
  2118. return false;
  2119. }
  2120. void kvm_vcpu_on_spin(struct kvm_vcpu *me, bool yield_to_kernel_mode)
  2121. {
  2122. struct kvm *kvm = me->kvm;
  2123. struct kvm_vcpu *vcpu;
  2124. int last_boosted_vcpu = me->kvm->last_boosted_vcpu;
  2125. int yielded = 0;
  2126. int try = 3;
  2127. int pass;
  2128. int i;
  2129. kvm_vcpu_set_in_spin_loop(me, true);
  2130. /*
  2131. * We boost the priority of a VCPU that is runnable but not
  2132. * currently running, because it got preempted by something
  2133. * else and called schedule in __vcpu_run. Hopefully that
  2134. * VCPU is holding the lock that we need and will release it.
  2135. * We approximate round-robin by starting at the last boosted VCPU.
  2136. */
  2137. for (pass = 0; pass < 2 && !yielded && try; pass++) {
  2138. kvm_for_each_vcpu(i, vcpu, kvm) {
  2139. if (!pass && i <= last_boosted_vcpu) {
  2140. i = last_boosted_vcpu;
  2141. continue;
  2142. } else if (pass && i > last_boosted_vcpu)
  2143. break;
  2144. if (!READ_ONCE(vcpu->preempted))
  2145. continue;
  2146. if (vcpu == me)
  2147. continue;
  2148. if (swait_active(&vcpu->wq) && !vcpu_dy_runnable(vcpu))
  2149. continue;
  2150. if (yield_to_kernel_mode && !kvm_arch_vcpu_in_kernel(vcpu))
  2151. continue;
  2152. if (!kvm_vcpu_eligible_for_directed_yield(vcpu))
  2153. continue;
  2154. yielded = kvm_vcpu_yield_to(vcpu);
  2155. if (yielded > 0) {
  2156. kvm->last_boosted_vcpu = i;
  2157. break;
  2158. } else if (yielded < 0) {
  2159. try--;
  2160. if (!try)
  2161. break;
  2162. }
  2163. }
  2164. }
  2165. kvm_vcpu_set_in_spin_loop(me, false);
  2166. /* Ensure vcpu is not eligible during next spinloop */
  2167. kvm_vcpu_set_dy_eligible(me, false);
  2168. }
  2169. EXPORT_SYMBOL_GPL(kvm_vcpu_on_spin);
  2170. static vm_fault_t kvm_vcpu_fault(struct vm_fault *vmf)
  2171. {
  2172. struct kvm_vcpu *vcpu = vmf->vma->vm_file->private_data;
  2173. struct page *page;
  2174. if (vmf->pgoff == 0)
  2175. page = virt_to_page(vcpu->run);
  2176. #ifdef CONFIG_X86
  2177. else if (vmf->pgoff == KVM_PIO_PAGE_OFFSET)
  2178. page = virt_to_page(vcpu->arch.pio_data);
  2179. #endif
  2180. #ifdef CONFIG_KVM_MMIO
  2181. else if (vmf->pgoff == KVM_COALESCED_MMIO_PAGE_OFFSET)
  2182. page = virt_to_page(vcpu->kvm->coalesced_mmio_ring);
  2183. #endif
  2184. else
  2185. return kvm_arch_vcpu_fault(vcpu, vmf);
  2186. get_page(page);
  2187. vmf->page = page;
  2188. return 0;
  2189. }
  2190. static const struct vm_operations_struct kvm_vcpu_vm_ops = {
  2191. .fault = kvm_vcpu_fault,
  2192. };
  2193. static int kvm_vcpu_mmap(struct file *file, struct vm_area_struct *vma)
  2194. {
  2195. vma->vm_ops = &kvm_vcpu_vm_ops;
  2196. return 0;
  2197. }
  2198. static int kvm_vcpu_release(struct inode *inode, struct file *filp)
  2199. {
  2200. struct kvm_vcpu *vcpu = filp->private_data;
  2201. debugfs_remove_recursive(vcpu->debugfs_dentry);
  2202. kvm_put_kvm(vcpu->kvm);
  2203. return 0;
  2204. }
  2205. static struct file_operations kvm_vcpu_fops = {
  2206. .release = kvm_vcpu_release,
  2207. .unlocked_ioctl = kvm_vcpu_ioctl,
  2208. .mmap = kvm_vcpu_mmap,
  2209. .llseek = noop_llseek,
  2210. KVM_COMPAT(kvm_vcpu_compat_ioctl),
  2211. };
  2212. /*
  2213. * Allocates an inode for the vcpu.
  2214. */
  2215. static int create_vcpu_fd(struct kvm_vcpu *vcpu)
  2216. {
  2217. char name[8 + 1 + ITOA_MAX_LEN + 1];
  2218. snprintf(name, sizeof(name), "kvm-vcpu:%d", vcpu->vcpu_id);
  2219. return anon_inode_getfd(name, &kvm_vcpu_fops, vcpu, O_RDWR | O_CLOEXEC);
  2220. }
  2221. static int kvm_create_vcpu_debugfs(struct kvm_vcpu *vcpu)
  2222. {
  2223. char dir_name[ITOA_MAX_LEN * 2];
  2224. int ret;
  2225. if (!kvm_arch_has_vcpu_debugfs())
  2226. return 0;
  2227. if (!debugfs_initialized())
  2228. return 0;
  2229. snprintf(dir_name, sizeof(dir_name), "vcpu%d", vcpu->vcpu_id);
  2230. vcpu->debugfs_dentry = debugfs_create_dir(dir_name,
  2231. vcpu->kvm->debugfs_dentry);
  2232. if (!vcpu->debugfs_dentry)
  2233. return -ENOMEM;
  2234. ret = kvm_arch_create_vcpu_debugfs(vcpu);
  2235. if (ret < 0) {
  2236. debugfs_remove_recursive(vcpu->debugfs_dentry);
  2237. return ret;
  2238. }
  2239. return 0;
  2240. }
  2241. /*
  2242. * Creates some virtual cpus. Good luck creating more than one.
  2243. */
  2244. static int kvm_vm_ioctl_create_vcpu(struct kvm *kvm, u32 id)
  2245. {
  2246. int r;
  2247. struct kvm_vcpu *vcpu;
  2248. if (id >= KVM_MAX_VCPU_ID)
  2249. return -EINVAL;
  2250. mutex_lock(&kvm->lock);
  2251. if (kvm->created_vcpus == KVM_MAX_VCPUS) {
  2252. mutex_unlock(&kvm->lock);
  2253. return -EINVAL;
  2254. }
  2255. kvm->created_vcpus++;
  2256. mutex_unlock(&kvm->lock);
  2257. vcpu = kvm_arch_vcpu_create(kvm, id);
  2258. if (IS_ERR(vcpu)) {
  2259. r = PTR_ERR(vcpu);
  2260. goto vcpu_decrement;
  2261. }
  2262. preempt_notifier_init(&vcpu->preempt_notifier, &kvm_preempt_ops);
  2263. r = kvm_arch_vcpu_setup(vcpu);
  2264. if (r)
  2265. goto vcpu_destroy;
  2266. r = kvm_create_vcpu_debugfs(vcpu);
  2267. if (r)
  2268. goto vcpu_destroy;
  2269. mutex_lock(&kvm->lock);
  2270. if (kvm_get_vcpu_by_id(kvm, id)) {
  2271. r = -EEXIST;
  2272. goto unlock_vcpu_destroy;
  2273. }
  2274. BUG_ON(kvm->vcpus[atomic_read(&kvm->online_vcpus)]);
  2275. /* Now it's all set up, let userspace reach it */
  2276. kvm_get_kvm(kvm);
  2277. r = create_vcpu_fd(vcpu);
  2278. if (r < 0) {
  2279. kvm_put_kvm(kvm);
  2280. goto unlock_vcpu_destroy;
  2281. }
  2282. kvm->vcpus[atomic_read(&kvm->online_vcpus)] = vcpu;
  2283. /*
  2284. * Pairs with smp_rmb() in kvm_get_vcpu. Write kvm->vcpus
  2285. * before kvm->online_vcpu's incremented value.
  2286. */
  2287. smp_wmb();
  2288. atomic_inc(&kvm->online_vcpus);
  2289. mutex_unlock(&kvm->lock);
  2290. kvm_arch_vcpu_postcreate(vcpu);
  2291. return r;
  2292. unlock_vcpu_destroy:
  2293. mutex_unlock(&kvm->lock);
  2294. debugfs_remove_recursive(vcpu->debugfs_dentry);
  2295. vcpu_destroy:
  2296. kvm_arch_vcpu_destroy(vcpu);
  2297. vcpu_decrement:
  2298. mutex_lock(&kvm->lock);
  2299. kvm->created_vcpus--;
  2300. mutex_unlock(&kvm->lock);
  2301. return r;
  2302. }
  2303. static int kvm_vcpu_ioctl_set_sigmask(struct kvm_vcpu *vcpu, sigset_t *sigset)
  2304. {
  2305. if (sigset) {
  2306. sigdelsetmask(sigset, sigmask(SIGKILL)|sigmask(SIGSTOP));
  2307. vcpu->sigset_active = 1;
  2308. vcpu->sigset = *sigset;
  2309. } else
  2310. vcpu->sigset_active = 0;
  2311. return 0;
  2312. }
  2313. static long kvm_vcpu_ioctl(struct file *filp,
  2314. unsigned int ioctl, unsigned long arg)
  2315. {
  2316. struct kvm_vcpu *vcpu = filp->private_data;
  2317. void __user *argp = (void __user *)arg;
  2318. int r;
  2319. struct kvm_fpu *fpu = NULL;
  2320. struct kvm_sregs *kvm_sregs = NULL;
  2321. if (vcpu->kvm->mm != current->mm)
  2322. return -EIO;
  2323. if (unlikely(_IOC_TYPE(ioctl) != KVMIO))
  2324. return -EINVAL;
  2325. /*
  2326. * Some architectures have vcpu ioctls that are asynchronous to vcpu
  2327. * execution; mutex_lock() would break them.
  2328. */
  2329. r = kvm_arch_vcpu_async_ioctl(filp, ioctl, arg);
  2330. if (r != -ENOIOCTLCMD)
  2331. return r;
  2332. if (mutex_lock_killable(&vcpu->mutex))
  2333. return -EINTR;
  2334. switch (ioctl) {
  2335. case KVM_RUN: {
  2336. struct pid *oldpid;
  2337. r = -EINVAL;
  2338. if (arg)
  2339. goto out;
  2340. oldpid = rcu_access_pointer(vcpu->pid);
  2341. if (unlikely(oldpid != task_pid(current))) {
  2342. /* The thread running this VCPU changed. */
  2343. struct pid *newpid;
  2344. r = kvm_arch_vcpu_run_pid_change(vcpu);
  2345. if (r)
  2346. break;
  2347. newpid = get_task_pid(current, PIDTYPE_PID);
  2348. rcu_assign_pointer(vcpu->pid, newpid);
  2349. if (oldpid)
  2350. synchronize_rcu();
  2351. put_pid(oldpid);
  2352. }
  2353. r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run);
  2354. trace_kvm_userspace_exit(vcpu->run->exit_reason, r);
  2355. break;
  2356. }
  2357. case KVM_GET_REGS: {
  2358. struct kvm_regs *kvm_regs;
  2359. r = -ENOMEM;
  2360. kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL);
  2361. if (!kvm_regs)
  2362. goto out;
  2363. r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs);
  2364. if (r)
  2365. goto out_free1;
  2366. r = -EFAULT;
  2367. if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs)))
  2368. goto out_free1;
  2369. r = 0;
  2370. out_free1:
  2371. kfree(kvm_regs);
  2372. break;
  2373. }
  2374. case KVM_SET_REGS: {
  2375. struct kvm_regs *kvm_regs;
  2376. r = -ENOMEM;
  2377. kvm_regs = memdup_user(argp, sizeof(*kvm_regs));
  2378. if (IS_ERR(kvm_regs)) {
  2379. r = PTR_ERR(kvm_regs);
  2380. goto out;
  2381. }
  2382. r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs);
  2383. kfree(kvm_regs);
  2384. break;
  2385. }
  2386. case KVM_GET_SREGS: {
  2387. kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL);
  2388. r = -ENOMEM;
  2389. if (!kvm_sregs)
  2390. goto out;
  2391. r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs);
  2392. if (r)
  2393. goto out;
  2394. r = -EFAULT;
  2395. if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs)))
  2396. goto out;
  2397. r = 0;
  2398. break;
  2399. }
  2400. case KVM_SET_SREGS: {
  2401. kvm_sregs = memdup_user(argp, sizeof(*kvm_sregs));
  2402. if (IS_ERR(kvm_sregs)) {
  2403. r = PTR_ERR(kvm_sregs);
  2404. kvm_sregs = NULL;
  2405. goto out;
  2406. }
  2407. r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs);
  2408. break;
  2409. }
  2410. case KVM_GET_MP_STATE: {
  2411. struct kvm_mp_state mp_state;
  2412. r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state);
  2413. if (r)
  2414. goto out;
  2415. r = -EFAULT;
  2416. if (copy_to_user(argp, &mp_state, sizeof(mp_state)))
  2417. goto out;
  2418. r = 0;
  2419. break;
  2420. }
  2421. case KVM_SET_MP_STATE: {
  2422. struct kvm_mp_state mp_state;
  2423. r = -EFAULT;
  2424. if (copy_from_user(&mp_state, argp, sizeof(mp_state)))
  2425. goto out;
  2426. r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state);
  2427. break;
  2428. }
  2429. case KVM_TRANSLATE: {
  2430. struct kvm_translation tr;
  2431. r = -EFAULT;
  2432. if (copy_from_user(&tr, argp, sizeof(tr)))
  2433. goto out;
  2434. r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr);
  2435. if (r)
  2436. goto out;
  2437. r = -EFAULT;
  2438. if (copy_to_user(argp, &tr, sizeof(tr)))
  2439. goto out;
  2440. r = 0;
  2441. break;
  2442. }
  2443. case KVM_SET_GUEST_DEBUG: {
  2444. struct kvm_guest_debug dbg;
  2445. r = -EFAULT;
  2446. if (copy_from_user(&dbg, argp, sizeof(dbg)))
  2447. goto out;
  2448. r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg);
  2449. break;
  2450. }
  2451. case KVM_SET_SIGNAL_MASK: {
  2452. struct kvm_signal_mask __user *sigmask_arg = argp;
  2453. struct kvm_signal_mask kvm_sigmask;
  2454. sigset_t sigset, *p;
  2455. p = NULL;
  2456. if (argp) {
  2457. r = -EFAULT;
  2458. if (copy_from_user(&kvm_sigmask, argp,
  2459. sizeof(kvm_sigmask)))
  2460. goto out;
  2461. r = -EINVAL;
  2462. if (kvm_sigmask.len != sizeof(sigset))
  2463. goto out;
  2464. r = -EFAULT;
  2465. if (copy_from_user(&sigset, sigmask_arg->sigset,
  2466. sizeof(sigset)))
  2467. goto out;
  2468. p = &sigset;
  2469. }
  2470. r = kvm_vcpu_ioctl_set_sigmask(vcpu, p);
  2471. break;
  2472. }
  2473. case KVM_GET_FPU: {
  2474. fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL);
  2475. r = -ENOMEM;
  2476. if (!fpu)
  2477. goto out;
  2478. r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu);
  2479. if (r)
  2480. goto out;
  2481. r = -EFAULT;
  2482. if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu)))
  2483. goto out;
  2484. r = 0;
  2485. break;
  2486. }
  2487. case KVM_SET_FPU: {
  2488. fpu = memdup_user(argp, sizeof(*fpu));
  2489. if (IS_ERR(fpu)) {
  2490. r = PTR_ERR(fpu);
  2491. fpu = NULL;
  2492. goto out;
  2493. }
  2494. r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu);
  2495. break;
  2496. }
  2497. default:
  2498. r = kvm_arch_vcpu_ioctl(filp, ioctl, arg);
  2499. }
  2500. out:
  2501. mutex_unlock(&vcpu->mutex);
  2502. kfree(fpu);
  2503. kfree(kvm_sregs);
  2504. return r;
  2505. }
  2506. #ifdef CONFIG_KVM_COMPAT
  2507. static long kvm_vcpu_compat_ioctl(struct file *filp,
  2508. unsigned int ioctl, unsigned long arg)
  2509. {
  2510. struct kvm_vcpu *vcpu = filp->private_data;
  2511. void __user *argp = compat_ptr(arg);
  2512. int r;
  2513. if (vcpu->kvm->mm != current->mm)
  2514. return -EIO;
  2515. switch (ioctl) {
  2516. case KVM_SET_SIGNAL_MASK: {
  2517. struct kvm_signal_mask __user *sigmask_arg = argp;
  2518. struct kvm_signal_mask kvm_sigmask;
  2519. sigset_t sigset;
  2520. if (argp) {
  2521. r = -EFAULT;
  2522. if (copy_from_user(&kvm_sigmask, argp,
  2523. sizeof(kvm_sigmask)))
  2524. goto out;
  2525. r = -EINVAL;
  2526. if (kvm_sigmask.len != sizeof(compat_sigset_t))
  2527. goto out;
  2528. r = -EFAULT;
  2529. if (get_compat_sigset(&sigset, (void *)sigmask_arg->sigset))
  2530. goto out;
  2531. r = kvm_vcpu_ioctl_set_sigmask(vcpu, &sigset);
  2532. } else
  2533. r = kvm_vcpu_ioctl_set_sigmask(vcpu, NULL);
  2534. break;
  2535. }
  2536. default:
  2537. r = kvm_vcpu_ioctl(filp, ioctl, arg);
  2538. }
  2539. out:
  2540. return r;
  2541. }
  2542. #endif
  2543. static int kvm_device_ioctl_attr(struct kvm_device *dev,
  2544. int (*accessor)(struct kvm_device *dev,
  2545. struct kvm_device_attr *attr),
  2546. unsigned long arg)
  2547. {
  2548. struct kvm_device_attr attr;
  2549. if (!accessor)
  2550. return -EPERM;
  2551. if (copy_from_user(&attr, (void __user *)arg, sizeof(attr)))
  2552. return -EFAULT;
  2553. return accessor(dev, &attr);
  2554. }
  2555. static long kvm_device_ioctl(struct file *filp, unsigned int ioctl,
  2556. unsigned long arg)
  2557. {
  2558. struct kvm_device *dev = filp->private_data;
  2559. if (dev->kvm->mm != current->mm)
  2560. return -EIO;
  2561. switch (ioctl) {
  2562. case KVM_SET_DEVICE_ATTR:
  2563. return kvm_device_ioctl_attr(dev, dev->ops->set_attr, arg);
  2564. case KVM_GET_DEVICE_ATTR:
  2565. return kvm_device_ioctl_attr(dev, dev->ops->get_attr, arg);
  2566. case KVM_HAS_DEVICE_ATTR:
  2567. return kvm_device_ioctl_attr(dev, dev->ops->has_attr, arg);
  2568. default:
  2569. if (dev->ops->ioctl)
  2570. return dev->ops->ioctl(dev, ioctl, arg);
  2571. return -ENOTTY;
  2572. }
  2573. }
  2574. static int kvm_device_release(struct inode *inode, struct file *filp)
  2575. {
  2576. struct kvm_device *dev = filp->private_data;
  2577. struct kvm *kvm = dev->kvm;
  2578. kvm_put_kvm(kvm);
  2579. return 0;
  2580. }
  2581. static const struct file_operations kvm_device_fops = {
  2582. .unlocked_ioctl = kvm_device_ioctl,
  2583. .release = kvm_device_release,
  2584. KVM_COMPAT(kvm_device_ioctl),
  2585. };
  2586. struct kvm_device *kvm_device_from_filp(struct file *filp)
  2587. {
  2588. if (filp->f_op != &kvm_device_fops)
  2589. return NULL;
  2590. return filp->private_data;
  2591. }
  2592. static struct kvm_device_ops *kvm_device_ops_table[KVM_DEV_TYPE_MAX] = {
  2593. #ifdef CONFIG_KVM_MPIC
  2594. [KVM_DEV_TYPE_FSL_MPIC_20] = &kvm_mpic_ops,
  2595. [KVM_DEV_TYPE_FSL_MPIC_42] = &kvm_mpic_ops,
  2596. #endif
  2597. };
  2598. int kvm_register_device_ops(struct kvm_device_ops *ops, u32 type)
  2599. {
  2600. if (type >= ARRAY_SIZE(kvm_device_ops_table))
  2601. return -ENOSPC;
  2602. if (kvm_device_ops_table[type] != NULL)
  2603. return -EEXIST;
  2604. kvm_device_ops_table[type] = ops;
  2605. return 0;
  2606. }
  2607. void kvm_unregister_device_ops(u32 type)
  2608. {
  2609. if (kvm_device_ops_table[type] != NULL)
  2610. kvm_device_ops_table[type] = NULL;
  2611. }
  2612. static int kvm_ioctl_create_device(struct kvm *kvm,
  2613. struct kvm_create_device *cd)
  2614. {
  2615. struct kvm_device_ops *ops = NULL;
  2616. struct kvm_device *dev;
  2617. bool test = cd->flags & KVM_CREATE_DEVICE_TEST;
  2618. int type;
  2619. int ret;
  2620. if (cd->type >= ARRAY_SIZE(kvm_device_ops_table))
  2621. return -ENODEV;
  2622. type = array_index_nospec(cd->type, ARRAY_SIZE(kvm_device_ops_table));
  2623. ops = kvm_device_ops_table[type];
  2624. if (ops == NULL)
  2625. return -ENODEV;
  2626. if (test)
  2627. return 0;
  2628. dev = kzalloc(sizeof(*dev), GFP_KERNEL);
  2629. if (!dev)
  2630. return -ENOMEM;
  2631. dev->ops = ops;
  2632. dev->kvm = kvm;
  2633. mutex_lock(&kvm->lock);
  2634. ret = ops->create(dev, type);
  2635. if (ret < 0) {
  2636. mutex_unlock(&kvm->lock);
  2637. kfree(dev);
  2638. return ret;
  2639. }
  2640. list_add(&dev->vm_node, &kvm->devices);
  2641. mutex_unlock(&kvm->lock);
  2642. if (ops->init)
  2643. ops->init(dev);
  2644. kvm_get_kvm(kvm);
  2645. ret = anon_inode_getfd(ops->name, &kvm_device_fops, dev, O_RDWR | O_CLOEXEC);
  2646. if (ret < 0) {
  2647. kvm_put_kvm(kvm);
  2648. mutex_lock(&kvm->lock);
  2649. list_del(&dev->vm_node);
  2650. mutex_unlock(&kvm->lock);
  2651. ops->destroy(dev);
  2652. return ret;
  2653. }
  2654. cd->fd = ret;
  2655. return 0;
  2656. }
  2657. static long kvm_vm_ioctl_check_extension_generic(struct kvm *kvm, long arg)
  2658. {
  2659. switch (arg) {
  2660. case KVM_CAP_USER_MEMORY:
  2661. case KVM_CAP_DESTROY_MEMORY_REGION_WORKS:
  2662. case KVM_CAP_JOIN_MEMORY_REGIONS_WORKS:
  2663. case KVM_CAP_INTERNAL_ERROR_DATA:
  2664. #ifdef CONFIG_HAVE_KVM_MSI
  2665. case KVM_CAP_SIGNAL_MSI:
  2666. #endif
  2667. #ifdef CONFIG_HAVE_KVM_IRQFD
  2668. case KVM_CAP_IRQFD:
  2669. case KVM_CAP_IRQFD_RESAMPLE:
  2670. #endif
  2671. case KVM_CAP_IOEVENTFD_ANY_LENGTH:
  2672. case KVM_CAP_CHECK_EXTENSION_VM:
  2673. return 1;
  2674. #ifdef CONFIG_KVM_MMIO
  2675. case KVM_CAP_COALESCED_MMIO:
  2676. return KVM_COALESCED_MMIO_PAGE_OFFSET;
  2677. #endif
  2678. #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
  2679. case KVM_CAP_IRQ_ROUTING:
  2680. return KVM_MAX_IRQ_ROUTES;
  2681. #endif
  2682. #if KVM_ADDRESS_SPACE_NUM > 1
  2683. case KVM_CAP_MULTI_ADDRESS_SPACE:
  2684. return KVM_ADDRESS_SPACE_NUM;
  2685. #endif
  2686. default:
  2687. break;
  2688. }
  2689. return kvm_vm_ioctl_check_extension(kvm, arg);
  2690. }
  2691. static long kvm_vm_ioctl(struct file *filp,
  2692. unsigned int ioctl, unsigned long arg)
  2693. {
  2694. struct kvm *kvm = filp->private_data;
  2695. void __user *argp = (void __user *)arg;
  2696. int r;
  2697. if (kvm->mm != current->mm)
  2698. return -EIO;
  2699. switch (ioctl) {
  2700. case KVM_CREATE_VCPU:
  2701. r = kvm_vm_ioctl_create_vcpu(kvm, arg);
  2702. break;
  2703. case KVM_SET_USER_MEMORY_REGION: {
  2704. struct kvm_userspace_memory_region kvm_userspace_mem;
  2705. r = -EFAULT;
  2706. if (copy_from_user(&kvm_userspace_mem, argp,
  2707. sizeof(kvm_userspace_mem)))
  2708. goto out;
  2709. r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem);
  2710. break;
  2711. }
  2712. case KVM_GET_DIRTY_LOG: {
  2713. struct kvm_dirty_log log;
  2714. r = -EFAULT;
  2715. if (copy_from_user(&log, argp, sizeof(log)))
  2716. goto out;
  2717. r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
  2718. break;
  2719. }
  2720. #ifdef CONFIG_KVM_MMIO
  2721. case KVM_REGISTER_COALESCED_MMIO: {
  2722. struct kvm_coalesced_mmio_zone zone;
  2723. r = -EFAULT;
  2724. if (copy_from_user(&zone, argp, sizeof(zone)))
  2725. goto out;
  2726. r = kvm_vm_ioctl_register_coalesced_mmio(kvm, &zone);
  2727. break;
  2728. }
  2729. case KVM_UNREGISTER_COALESCED_MMIO: {
  2730. struct kvm_coalesced_mmio_zone zone;
  2731. r = -EFAULT;
  2732. if (copy_from_user(&zone, argp, sizeof(zone)))
  2733. goto out;
  2734. r = kvm_vm_ioctl_unregister_coalesced_mmio(kvm, &zone);
  2735. break;
  2736. }
  2737. #endif
  2738. case KVM_IRQFD: {
  2739. struct kvm_irqfd data;
  2740. r = -EFAULT;
  2741. if (copy_from_user(&data, argp, sizeof(data)))
  2742. goto out;
  2743. r = kvm_irqfd(kvm, &data);
  2744. break;
  2745. }
  2746. case KVM_IOEVENTFD: {
  2747. struct kvm_ioeventfd data;
  2748. r = -EFAULT;
  2749. if (copy_from_user(&data, argp, sizeof(data)))
  2750. goto out;
  2751. r = kvm_ioeventfd(kvm, &data);
  2752. break;
  2753. }
  2754. #ifdef CONFIG_HAVE_KVM_MSI
  2755. case KVM_SIGNAL_MSI: {
  2756. struct kvm_msi msi;
  2757. r = -EFAULT;
  2758. if (copy_from_user(&msi, argp, sizeof(msi)))
  2759. goto out;
  2760. r = kvm_send_userspace_msi(kvm, &msi);
  2761. break;
  2762. }
  2763. #endif
  2764. #ifdef __KVM_HAVE_IRQ_LINE
  2765. case KVM_IRQ_LINE_STATUS:
  2766. case KVM_IRQ_LINE: {
  2767. struct kvm_irq_level irq_event;
  2768. r = -EFAULT;
  2769. if (copy_from_user(&irq_event, argp, sizeof(irq_event)))
  2770. goto out;
  2771. r = kvm_vm_ioctl_irq_line(kvm, &irq_event,
  2772. ioctl == KVM_IRQ_LINE_STATUS);
  2773. if (r)
  2774. goto out;
  2775. r = -EFAULT;
  2776. if (ioctl == KVM_IRQ_LINE_STATUS) {
  2777. if (copy_to_user(argp, &irq_event, sizeof(irq_event)))
  2778. goto out;
  2779. }
  2780. r = 0;
  2781. break;
  2782. }
  2783. #endif
  2784. #ifdef CONFIG_HAVE_KVM_IRQ_ROUTING
  2785. case KVM_SET_GSI_ROUTING: {
  2786. struct kvm_irq_routing routing;
  2787. struct kvm_irq_routing __user *urouting;
  2788. struct kvm_irq_routing_entry *entries = NULL;
  2789. r = -EFAULT;
  2790. if (copy_from_user(&routing, argp, sizeof(routing)))
  2791. goto out;
  2792. r = -EINVAL;
  2793. if (!kvm_arch_can_set_irq_routing(kvm))
  2794. goto out;
  2795. if (routing.nr > KVM_MAX_IRQ_ROUTES)
  2796. goto out;
  2797. if (routing.flags)
  2798. goto out;
  2799. if (routing.nr) {
  2800. r = -ENOMEM;
  2801. entries = vmalloc(array_size(sizeof(*entries),
  2802. routing.nr));
  2803. if (!entries)
  2804. goto out;
  2805. r = -EFAULT;
  2806. urouting = argp;
  2807. if (copy_from_user(entries, urouting->entries,
  2808. routing.nr * sizeof(*entries)))
  2809. goto out_free_irq_routing;
  2810. }
  2811. r = kvm_set_irq_routing(kvm, entries, routing.nr,
  2812. routing.flags);
  2813. out_free_irq_routing:
  2814. vfree(entries);
  2815. break;
  2816. }
  2817. #endif /* CONFIG_HAVE_KVM_IRQ_ROUTING */
  2818. case KVM_CREATE_DEVICE: {
  2819. struct kvm_create_device cd;
  2820. r = -EFAULT;
  2821. if (copy_from_user(&cd, argp, sizeof(cd)))
  2822. goto out;
  2823. r = kvm_ioctl_create_device(kvm, &cd);
  2824. if (r)
  2825. goto out;
  2826. r = -EFAULT;
  2827. if (copy_to_user(argp, &cd, sizeof(cd)))
  2828. goto out;
  2829. r = 0;
  2830. break;
  2831. }
  2832. case KVM_CHECK_EXTENSION:
  2833. r = kvm_vm_ioctl_check_extension_generic(kvm, arg);
  2834. break;
  2835. default:
  2836. r = kvm_arch_vm_ioctl(filp, ioctl, arg);
  2837. }
  2838. out:
  2839. return r;
  2840. }
  2841. #ifdef CONFIG_KVM_COMPAT
  2842. struct compat_kvm_dirty_log {
  2843. __u32 slot;
  2844. __u32 padding1;
  2845. union {
  2846. compat_uptr_t dirty_bitmap; /* one bit per page */
  2847. __u64 padding2;
  2848. };
  2849. };
  2850. static long kvm_vm_compat_ioctl(struct file *filp,
  2851. unsigned int ioctl, unsigned long arg)
  2852. {
  2853. struct kvm *kvm = filp->private_data;
  2854. int r;
  2855. if (kvm->mm != current->mm)
  2856. return -EIO;
  2857. switch (ioctl) {
  2858. case KVM_GET_DIRTY_LOG: {
  2859. struct compat_kvm_dirty_log compat_log;
  2860. struct kvm_dirty_log log;
  2861. if (copy_from_user(&compat_log, (void __user *)arg,
  2862. sizeof(compat_log)))
  2863. return -EFAULT;
  2864. log.slot = compat_log.slot;
  2865. log.padding1 = compat_log.padding1;
  2866. log.padding2 = compat_log.padding2;
  2867. log.dirty_bitmap = compat_ptr(compat_log.dirty_bitmap);
  2868. r = kvm_vm_ioctl_get_dirty_log(kvm, &log);
  2869. break;
  2870. }
  2871. default:
  2872. r = kvm_vm_ioctl(filp, ioctl, arg);
  2873. }
  2874. return r;
  2875. }
  2876. #endif
  2877. static struct file_operations kvm_vm_fops = {
  2878. .release = kvm_vm_release,
  2879. .unlocked_ioctl = kvm_vm_ioctl,
  2880. .llseek = noop_llseek,
  2881. KVM_COMPAT(kvm_vm_compat_ioctl),
  2882. };
  2883. static int kvm_dev_ioctl_create_vm(unsigned long type)
  2884. {
  2885. int r;
  2886. struct kvm *kvm;
  2887. struct file *file;
  2888. kvm = kvm_create_vm(type);
  2889. if (IS_ERR(kvm))
  2890. return PTR_ERR(kvm);
  2891. #ifdef CONFIG_KVM_MMIO
  2892. r = kvm_coalesced_mmio_init(kvm);
  2893. if (r < 0)
  2894. goto put_kvm;
  2895. #endif
  2896. r = get_unused_fd_flags(O_CLOEXEC);
  2897. if (r < 0)
  2898. goto put_kvm;
  2899. file = anon_inode_getfile("kvm-vm", &kvm_vm_fops, kvm, O_RDWR);
  2900. if (IS_ERR(file)) {
  2901. put_unused_fd(r);
  2902. r = PTR_ERR(file);
  2903. goto put_kvm;
  2904. }
  2905. /*
  2906. * Don't call kvm_put_kvm anymore at this point; file->f_op is
  2907. * already set, with ->release() being kvm_vm_release(). In error
  2908. * cases it will be called by the final fput(file) and will take
  2909. * care of doing kvm_put_kvm(kvm).
  2910. */
  2911. if (kvm_create_vm_debugfs(kvm, r) < 0) {
  2912. put_unused_fd(r);
  2913. fput(file);
  2914. return -ENOMEM;
  2915. }
  2916. kvm_uevent_notify_change(KVM_EVENT_CREATE_VM, kvm);
  2917. fd_install(r, file);
  2918. return r;
  2919. put_kvm:
  2920. kvm_put_kvm(kvm);
  2921. return r;
  2922. }
  2923. static long kvm_dev_ioctl(struct file *filp,
  2924. unsigned int ioctl, unsigned long arg)
  2925. {
  2926. long r = -EINVAL;
  2927. switch (ioctl) {
  2928. case KVM_GET_API_VERSION:
  2929. if (arg)
  2930. goto out;
  2931. r = KVM_API_VERSION;
  2932. break;
  2933. case KVM_CREATE_VM:
  2934. r = kvm_dev_ioctl_create_vm(arg);
  2935. break;
  2936. case KVM_CHECK_EXTENSION:
  2937. r = kvm_vm_ioctl_check_extension_generic(NULL, arg);
  2938. break;
  2939. case KVM_GET_VCPU_MMAP_SIZE:
  2940. if (arg)
  2941. goto out;
  2942. r = PAGE_SIZE; /* struct kvm_run */
  2943. #ifdef CONFIG_X86
  2944. r += PAGE_SIZE; /* pio data page */
  2945. #endif
  2946. #ifdef CONFIG_KVM_MMIO
  2947. r += PAGE_SIZE; /* coalesced mmio ring page */
  2948. #endif
  2949. break;
  2950. case KVM_TRACE_ENABLE:
  2951. case KVM_TRACE_PAUSE:
  2952. case KVM_TRACE_DISABLE:
  2953. r = -EOPNOTSUPP;
  2954. break;
  2955. default:
  2956. return kvm_arch_dev_ioctl(filp, ioctl, arg);
  2957. }
  2958. out:
  2959. return r;
  2960. }
  2961. static struct file_operations kvm_chardev_ops = {
  2962. .unlocked_ioctl = kvm_dev_ioctl,
  2963. .llseek = noop_llseek,
  2964. KVM_COMPAT(kvm_dev_ioctl),
  2965. };
  2966. static struct miscdevice kvm_dev = {
  2967. KVM_MINOR,
  2968. "kvm",
  2969. &kvm_chardev_ops,
  2970. };
  2971. static void hardware_enable_nolock(void *junk)
  2972. {
  2973. int cpu = raw_smp_processor_id();
  2974. int r;
  2975. if (cpumask_test_cpu(cpu, cpus_hardware_enabled))
  2976. return;
  2977. cpumask_set_cpu(cpu, cpus_hardware_enabled);
  2978. r = kvm_arch_hardware_enable();
  2979. if (r) {
  2980. cpumask_clear_cpu(cpu, cpus_hardware_enabled);
  2981. atomic_inc(&hardware_enable_failed);
  2982. pr_info("kvm: enabling virtualization on CPU%d failed\n", cpu);
  2983. }
  2984. }
  2985. static int kvm_starting_cpu(unsigned int cpu)
  2986. {
  2987. raw_spin_lock(&kvm_count_lock);
  2988. if (kvm_usage_count)
  2989. hardware_enable_nolock(NULL);
  2990. raw_spin_unlock(&kvm_count_lock);
  2991. return 0;
  2992. }
  2993. static void hardware_disable_nolock(void *junk)
  2994. {
  2995. int cpu = raw_smp_processor_id();
  2996. if (!cpumask_test_cpu(cpu, cpus_hardware_enabled))
  2997. return;
  2998. cpumask_clear_cpu(cpu, cpus_hardware_enabled);
  2999. kvm_arch_hardware_disable();
  3000. }
  3001. static int kvm_dying_cpu(unsigned int cpu)
  3002. {
  3003. raw_spin_lock(&kvm_count_lock);
  3004. if (kvm_usage_count)
  3005. hardware_disable_nolock(NULL);
  3006. raw_spin_unlock(&kvm_count_lock);
  3007. return 0;
  3008. }
  3009. static void hardware_disable_all_nolock(void)
  3010. {
  3011. BUG_ON(!kvm_usage_count);
  3012. kvm_usage_count--;
  3013. if (!kvm_usage_count)
  3014. on_each_cpu(hardware_disable_nolock, NULL, 1);
  3015. }
  3016. static void hardware_disable_all(void)
  3017. {
  3018. raw_spin_lock(&kvm_count_lock);
  3019. hardware_disable_all_nolock();
  3020. raw_spin_unlock(&kvm_count_lock);
  3021. }
  3022. static int hardware_enable_all(void)
  3023. {
  3024. int r = 0;
  3025. raw_spin_lock(&kvm_count_lock);
  3026. kvm_usage_count++;
  3027. if (kvm_usage_count == 1) {
  3028. atomic_set(&hardware_enable_failed, 0);
  3029. on_each_cpu(hardware_enable_nolock, NULL, 1);
  3030. if (atomic_read(&hardware_enable_failed)) {
  3031. hardware_disable_all_nolock();
  3032. r = -EBUSY;
  3033. }
  3034. }
  3035. raw_spin_unlock(&kvm_count_lock);
  3036. return r;
  3037. }
  3038. static int kvm_reboot(struct notifier_block *notifier, unsigned long val,
  3039. void *v)
  3040. {
  3041. /*
  3042. * Some (well, at least mine) BIOSes hang on reboot if
  3043. * in vmx root mode.
  3044. *
  3045. * And Intel TXT required VMX off for all cpu when system shutdown.
  3046. */
  3047. pr_info("kvm: exiting hardware virtualization\n");
  3048. kvm_rebooting = true;
  3049. on_each_cpu(hardware_disable_nolock, NULL, 1);
  3050. return NOTIFY_OK;
  3051. }
  3052. static struct notifier_block kvm_reboot_notifier = {
  3053. .notifier_call = kvm_reboot,
  3054. .priority = 0,
  3055. };
  3056. static void kvm_io_bus_destroy(struct kvm_io_bus *bus)
  3057. {
  3058. int i;
  3059. for (i = 0; i < bus->dev_count; i++) {
  3060. struct kvm_io_device *pos = bus->range[i].dev;
  3061. kvm_iodevice_destructor(pos);
  3062. }
  3063. kfree(bus);
  3064. }
  3065. static inline int kvm_io_bus_cmp(const struct kvm_io_range *r1,
  3066. const struct kvm_io_range *r2)
  3067. {
  3068. gpa_t addr1 = r1->addr;
  3069. gpa_t addr2 = r2->addr;
  3070. if (addr1 < addr2)
  3071. return -1;
  3072. /* If r2->len == 0, match the exact address. If r2->len != 0,
  3073. * accept any overlapping write. Any order is acceptable for
  3074. * overlapping ranges, because kvm_io_bus_get_first_dev ensures
  3075. * we process all of them.
  3076. */
  3077. if (r2->len) {
  3078. addr1 += r1->len;
  3079. addr2 += r2->len;
  3080. }
  3081. if (addr1 > addr2)
  3082. return 1;
  3083. return 0;
  3084. }
  3085. static int kvm_io_bus_sort_cmp(const void *p1, const void *p2)
  3086. {
  3087. return kvm_io_bus_cmp(p1, p2);
  3088. }
  3089. static int kvm_io_bus_get_first_dev(struct kvm_io_bus *bus,
  3090. gpa_t addr, int len)
  3091. {
  3092. struct kvm_io_range *range, key;
  3093. int off;
  3094. key = (struct kvm_io_range) {
  3095. .addr = addr,
  3096. .len = len,
  3097. };
  3098. range = bsearch(&key, bus->range, bus->dev_count,
  3099. sizeof(struct kvm_io_range), kvm_io_bus_sort_cmp);
  3100. if (range == NULL)
  3101. return -ENOENT;
  3102. off = range - bus->range;
  3103. while (off > 0 && kvm_io_bus_cmp(&key, &bus->range[off-1]) == 0)
  3104. off--;
  3105. return off;
  3106. }
  3107. static int __kvm_io_bus_write(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
  3108. struct kvm_io_range *range, const void *val)
  3109. {
  3110. int idx;
  3111. idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
  3112. if (idx < 0)
  3113. return -EOPNOTSUPP;
  3114. while (idx < bus->dev_count &&
  3115. kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
  3116. if (!kvm_iodevice_write(vcpu, bus->range[idx].dev, range->addr,
  3117. range->len, val))
  3118. return idx;
  3119. idx++;
  3120. }
  3121. return -EOPNOTSUPP;
  3122. }
  3123. /* kvm_io_bus_write - called under kvm->slots_lock */
  3124. int kvm_io_bus_write(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
  3125. int len, const void *val)
  3126. {
  3127. struct kvm_io_bus *bus;
  3128. struct kvm_io_range range;
  3129. int r;
  3130. range = (struct kvm_io_range) {
  3131. .addr = addr,
  3132. .len = len,
  3133. };
  3134. bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
  3135. if (!bus)
  3136. return -ENOMEM;
  3137. r = __kvm_io_bus_write(vcpu, bus, &range, val);
  3138. return r < 0 ? r : 0;
  3139. }
  3140. /* kvm_io_bus_write_cookie - called under kvm->slots_lock */
  3141. int kvm_io_bus_write_cookie(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx,
  3142. gpa_t addr, int len, const void *val, long cookie)
  3143. {
  3144. struct kvm_io_bus *bus;
  3145. struct kvm_io_range range;
  3146. range = (struct kvm_io_range) {
  3147. .addr = addr,
  3148. .len = len,
  3149. };
  3150. bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
  3151. if (!bus)
  3152. return -ENOMEM;
  3153. /* First try the device referenced by cookie. */
  3154. if ((cookie >= 0) && (cookie < bus->dev_count) &&
  3155. (kvm_io_bus_cmp(&range, &bus->range[cookie]) == 0))
  3156. if (!kvm_iodevice_write(vcpu, bus->range[cookie].dev, addr, len,
  3157. val))
  3158. return cookie;
  3159. /*
  3160. * cookie contained garbage; fall back to search and return the
  3161. * correct cookie value.
  3162. */
  3163. return __kvm_io_bus_write(vcpu, bus, &range, val);
  3164. }
  3165. static int __kvm_io_bus_read(struct kvm_vcpu *vcpu, struct kvm_io_bus *bus,
  3166. struct kvm_io_range *range, void *val)
  3167. {
  3168. int idx;
  3169. idx = kvm_io_bus_get_first_dev(bus, range->addr, range->len);
  3170. if (idx < 0)
  3171. return -EOPNOTSUPP;
  3172. while (idx < bus->dev_count &&
  3173. kvm_io_bus_cmp(range, &bus->range[idx]) == 0) {
  3174. if (!kvm_iodevice_read(vcpu, bus->range[idx].dev, range->addr,
  3175. range->len, val))
  3176. return idx;
  3177. idx++;
  3178. }
  3179. return -EOPNOTSUPP;
  3180. }
  3181. EXPORT_SYMBOL_GPL(kvm_io_bus_write);
  3182. /* kvm_io_bus_read - called under kvm->slots_lock */
  3183. int kvm_io_bus_read(struct kvm_vcpu *vcpu, enum kvm_bus bus_idx, gpa_t addr,
  3184. int len, void *val)
  3185. {
  3186. struct kvm_io_bus *bus;
  3187. struct kvm_io_range range;
  3188. int r;
  3189. range = (struct kvm_io_range) {
  3190. .addr = addr,
  3191. .len = len,
  3192. };
  3193. bus = srcu_dereference(vcpu->kvm->buses[bus_idx], &vcpu->kvm->srcu);
  3194. if (!bus)
  3195. return -ENOMEM;
  3196. r = __kvm_io_bus_read(vcpu, bus, &range, val);
  3197. return r < 0 ? r : 0;
  3198. }
  3199. /* Caller must hold slots_lock. */
  3200. int kvm_io_bus_register_dev(struct kvm *kvm, enum kvm_bus bus_idx, gpa_t addr,
  3201. int len, struct kvm_io_device *dev)
  3202. {
  3203. int i;
  3204. struct kvm_io_bus *new_bus, *bus;
  3205. struct kvm_io_range range;
  3206. bus = kvm_get_bus(kvm, bus_idx);
  3207. if (!bus)
  3208. return -ENOMEM;
  3209. /* exclude ioeventfd which is limited by maximum fd */
  3210. if (bus->dev_count - bus->ioeventfd_count > NR_IOBUS_DEVS - 1)
  3211. return -ENOSPC;
  3212. new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count + 1) *
  3213. sizeof(struct kvm_io_range)), GFP_KERNEL);
  3214. if (!new_bus)
  3215. return -ENOMEM;
  3216. range = (struct kvm_io_range) {
  3217. .addr = addr,
  3218. .len = len,
  3219. .dev = dev,
  3220. };
  3221. for (i = 0; i < bus->dev_count; i++)
  3222. if (kvm_io_bus_cmp(&bus->range[i], &range) > 0)
  3223. break;
  3224. memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
  3225. new_bus->dev_count++;
  3226. new_bus->range[i] = range;
  3227. memcpy(new_bus->range + i + 1, bus->range + i,
  3228. (bus->dev_count - i) * sizeof(struct kvm_io_range));
  3229. rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
  3230. synchronize_srcu_expedited(&kvm->srcu);
  3231. kfree(bus);
  3232. return 0;
  3233. }
  3234. /* Caller must hold slots_lock. */
  3235. void kvm_io_bus_unregister_dev(struct kvm *kvm, enum kvm_bus bus_idx,
  3236. struct kvm_io_device *dev)
  3237. {
  3238. int i, j;
  3239. struct kvm_io_bus *new_bus, *bus;
  3240. bus = kvm_get_bus(kvm, bus_idx);
  3241. if (!bus)
  3242. return;
  3243. for (i = 0; i < bus->dev_count; i++)
  3244. if (bus->range[i].dev == dev) {
  3245. break;
  3246. }
  3247. if (i == bus->dev_count)
  3248. return;
  3249. new_bus = kmalloc(sizeof(*bus) + ((bus->dev_count - 1) *
  3250. sizeof(struct kvm_io_range)), GFP_KERNEL);
  3251. if (new_bus) {
  3252. memcpy(new_bus, bus, sizeof(*bus) + i * sizeof(struct kvm_io_range));
  3253. new_bus->dev_count--;
  3254. memcpy(new_bus->range + i, bus->range + i + 1,
  3255. (new_bus->dev_count - i) * sizeof(struct kvm_io_range));
  3256. } else {
  3257. pr_err("kvm: failed to shrink bus, removing it completely\n");
  3258. for (j = 0; j < bus->dev_count; j++) {
  3259. if (j == i)
  3260. continue;
  3261. kvm_iodevice_destructor(bus->range[j].dev);
  3262. }
  3263. }
  3264. rcu_assign_pointer(kvm->buses[bus_idx], new_bus);
  3265. synchronize_srcu_expedited(&kvm->srcu);
  3266. kfree(bus);
  3267. return;
  3268. }
  3269. struct kvm_io_device *kvm_io_bus_get_dev(struct kvm *kvm, enum kvm_bus bus_idx,
  3270. gpa_t addr)
  3271. {
  3272. struct kvm_io_bus *bus;
  3273. int dev_idx, srcu_idx;
  3274. struct kvm_io_device *iodev = NULL;
  3275. srcu_idx = srcu_read_lock(&kvm->srcu);
  3276. bus = srcu_dereference(kvm->buses[bus_idx], &kvm->srcu);
  3277. if (!bus)
  3278. goto out_unlock;
  3279. dev_idx = kvm_io_bus_get_first_dev(bus, addr, 1);
  3280. if (dev_idx < 0)
  3281. goto out_unlock;
  3282. iodev = bus->range[dev_idx].dev;
  3283. out_unlock:
  3284. srcu_read_unlock(&kvm->srcu, srcu_idx);
  3285. return iodev;
  3286. }
  3287. EXPORT_SYMBOL_GPL(kvm_io_bus_get_dev);
  3288. static int kvm_debugfs_open(struct inode *inode, struct file *file,
  3289. int (*get)(void *, u64 *), int (*set)(void *, u64),
  3290. const char *fmt)
  3291. {
  3292. struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
  3293. inode->i_private;
  3294. /* The debugfs files are a reference to the kvm struct which
  3295. * is still valid when kvm_destroy_vm is called.
  3296. * To avoid the race between open and the removal of the debugfs
  3297. * directory we test against the users count.
  3298. */
  3299. if (!refcount_inc_not_zero(&stat_data->kvm->users_count))
  3300. return -ENOENT;
  3301. if (simple_attr_open(inode, file, get,
  3302. stat_data->mode & S_IWUGO ? set : NULL,
  3303. fmt)) {
  3304. kvm_put_kvm(stat_data->kvm);
  3305. return -ENOMEM;
  3306. }
  3307. return 0;
  3308. }
  3309. static int kvm_debugfs_release(struct inode *inode, struct file *file)
  3310. {
  3311. struct kvm_stat_data *stat_data = (struct kvm_stat_data *)
  3312. inode->i_private;
  3313. simple_attr_release(inode, file);
  3314. kvm_put_kvm(stat_data->kvm);
  3315. return 0;
  3316. }
  3317. static int vm_stat_get_per_vm(void *data, u64 *val)
  3318. {
  3319. struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
  3320. *val = *(ulong *)((void *)stat_data->kvm + stat_data->offset);
  3321. return 0;
  3322. }
  3323. static int vm_stat_clear_per_vm(void *data, u64 val)
  3324. {
  3325. struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
  3326. if (val)
  3327. return -EINVAL;
  3328. *(ulong *)((void *)stat_data->kvm + stat_data->offset) = 0;
  3329. return 0;
  3330. }
  3331. static int vm_stat_get_per_vm_open(struct inode *inode, struct file *file)
  3332. {
  3333. __simple_attr_check_format("%llu\n", 0ull);
  3334. return kvm_debugfs_open(inode, file, vm_stat_get_per_vm,
  3335. vm_stat_clear_per_vm, "%llu\n");
  3336. }
  3337. static const struct file_operations vm_stat_get_per_vm_fops = {
  3338. .owner = THIS_MODULE,
  3339. .open = vm_stat_get_per_vm_open,
  3340. .release = kvm_debugfs_release,
  3341. .read = simple_attr_read,
  3342. .write = simple_attr_write,
  3343. .llseek = no_llseek,
  3344. };
  3345. static int vcpu_stat_get_per_vm(void *data, u64 *val)
  3346. {
  3347. int i;
  3348. struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
  3349. struct kvm_vcpu *vcpu;
  3350. *val = 0;
  3351. kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
  3352. *val += *(u64 *)((void *)vcpu + stat_data->offset);
  3353. return 0;
  3354. }
  3355. static int vcpu_stat_clear_per_vm(void *data, u64 val)
  3356. {
  3357. int i;
  3358. struct kvm_stat_data *stat_data = (struct kvm_stat_data *)data;
  3359. struct kvm_vcpu *vcpu;
  3360. if (val)
  3361. return -EINVAL;
  3362. kvm_for_each_vcpu(i, vcpu, stat_data->kvm)
  3363. *(u64 *)((void *)vcpu + stat_data->offset) = 0;
  3364. return 0;
  3365. }
  3366. static int vcpu_stat_get_per_vm_open(struct inode *inode, struct file *file)
  3367. {
  3368. __simple_attr_check_format("%llu\n", 0ull);
  3369. return kvm_debugfs_open(inode, file, vcpu_stat_get_per_vm,
  3370. vcpu_stat_clear_per_vm, "%llu\n");
  3371. }
  3372. static const struct file_operations vcpu_stat_get_per_vm_fops = {
  3373. .owner = THIS_MODULE,
  3374. .open = vcpu_stat_get_per_vm_open,
  3375. .release = kvm_debugfs_release,
  3376. .read = simple_attr_read,
  3377. .write = simple_attr_write,
  3378. .llseek = no_llseek,
  3379. };
  3380. static const struct file_operations *stat_fops_per_vm[] = {
  3381. [KVM_STAT_VCPU] = &vcpu_stat_get_per_vm_fops,
  3382. [KVM_STAT_VM] = &vm_stat_get_per_vm_fops,
  3383. };
  3384. static int vm_stat_get(void *_offset, u64 *val)
  3385. {
  3386. unsigned offset = (long)_offset;
  3387. struct kvm *kvm;
  3388. struct kvm_stat_data stat_tmp = {.offset = offset};
  3389. u64 tmp_val;
  3390. *val = 0;
  3391. mutex_lock(&kvm_lock);
  3392. list_for_each_entry(kvm, &vm_list, vm_list) {
  3393. stat_tmp.kvm = kvm;
  3394. vm_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
  3395. *val += tmp_val;
  3396. }
  3397. mutex_unlock(&kvm_lock);
  3398. return 0;
  3399. }
  3400. static int vm_stat_clear(void *_offset, u64 val)
  3401. {
  3402. unsigned offset = (long)_offset;
  3403. struct kvm *kvm;
  3404. struct kvm_stat_data stat_tmp = {.offset = offset};
  3405. if (val)
  3406. return -EINVAL;
  3407. mutex_lock(&kvm_lock);
  3408. list_for_each_entry(kvm, &vm_list, vm_list) {
  3409. stat_tmp.kvm = kvm;
  3410. vm_stat_clear_per_vm((void *)&stat_tmp, 0);
  3411. }
  3412. mutex_unlock(&kvm_lock);
  3413. return 0;
  3414. }
  3415. DEFINE_SIMPLE_ATTRIBUTE(vm_stat_fops, vm_stat_get, vm_stat_clear, "%llu\n");
  3416. static int vcpu_stat_get(void *_offset, u64 *val)
  3417. {
  3418. unsigned offset = (long)_offset;
  3419. struct kvm *kvm;
  3420. struct kvm_stat_data stat_tmp = {.offset = offset};
  3421. u64 tmp_val;
  3422. *val = 0;
  3423. mutex_lock(&kvm_lock);
  3424. list_for_each_entry(kvm, &vm_list, vm_list) {
  3425. stat_tmp.kvm = kvm;
  3426. vcpu_stat_get_per_vm((void *)&stat_tmp, &tmp_val);
  3427. *val += tmp_val;
  3428. }
  3429. mutex_unlock(&kvm_lock);
  3430. return 0;
  3431. }
  3432. static int vcpu_stat_clear(void *_offset, u64 val)
  3433. {
  3434. unsigned offset = (long)_offset;
  3435. struct kvm *kvm;
  3436. struct kvm_stat_data stat_tmp = {.offset = offset};
  3437. if (val)
  3438. return -EINVAL;
  3439. mutex_lock(&kvm_lock);
  3440. list_for_each_entry(kvm, &vm_list, vm_list) {
  3441. stat_tmp.kvm = kvm;
  3442. vcpu_stat_clear_per_vm((void *)&stat_tmp, 0);
  3443. }
  3444. mutex_unlock(&kvm_lock);
  3445. return 0;
  3446. }
  3447. DEFINE_SIMPLE_ATTRIBUTE(vcpu_stat_fops, vcpu_stat_get, vcpu_stat_clear,
  3448. "%llu\n");
  3449. static const struct file_operations *stat_fops[] = {
  3450. [KVM_STAT_VCPU] = &vcpu_stat_fops,
  3451. [KVM_STAT_VM] = &vm_stat_fops,
  3452. };
  3453. static void kvm_uevent_notify_change(unsigned int type, struct kvm *kvm)
  3454. {
  3455. struct kobj_uevent_env *env;
  3456. unsigned long long created, active;
  3457. if (!kvm_dev.this_device || !kvm)
  3458. return;
  3459. mutex_lock(&kvm_lock);
  3460. if (type == KVM_EVENT_CREATE_VM) {
  3461. kvm_createvm_count++;
  3462. kvm_active_vms++;
  3463. } else if (type == KVM_EVENT_DESTROY_VM) {
  3464. kvm_active_vms--;
  3465. }
  3466. created = kvm_createvm_count;
  3467. active = kvm_active_vms;
  3468. mutex_unlock(&kvm_lock);
  3469. env = kzalloc(sizeof(*env), GFP_KERNEL);
  3470. if (!env)
  3471. return;
  3472. add_uevent_var(env, "CREATED=%llu", created);
  3473. add_uevent_var(env, "COUNT=%llu", active);
  3474. if (type == KVM_EVENT_CREATE_VM) {
  3475. add_uevent_var(env, "EVENT=create");
  3476. kvm->userspace_pid = task_pid_nr(current);
  3477. } else if (type == KVM_EVENT_DESTROY_VM) {
  3478. add_uevent_var(env, "EVENT=destroy");
  3479. }
  3480. add_uevent_var(env, "PID=%d", kvm->userspace_pid);
  3481. if (!IS_ERR_OR_NULL(kvm->debugfs_dentry)) {
  3482. char *tmp, *p = kmalloc(PATH_MAX, GFP_KERNEL);
  3483. if (p) {
  3484. tmp = dentry_path_raw(kvm->debugfs_dentry, p, PATH_MAX);
  3485. if (!IS_ERR(tmp))
  3486. add_uevent_var(env, "STATS_PATH=%s", tmp);
  3487. kfree(p);
  3488. }
  3489. }
  3490. /* no need for checks, since we are adding at most only 5 keys */
  3491. env->envp[env->envp_idx++] = NULL;
  3492. kobject_uevent_env(&kvm_dev.this_device->kobj, KOBJ_CHANGE, env->envp);
  3493. kfree(env);
  3494. }
  3495. static void kvm_init_debug(void)
  3496. {
  3497. struct kvm_stats_debugfs_item *p;
  3498. kvm_debugfs_dir = debugfs_create_dir("kvm", NULL);
  3499. kvm_debugfs_num_entries = 0;
  3500. for (p = debugfs_entries; p->name; ++p, kvm_debugfs_num_entries++) {
  3501. int mode = p->mode ? p->mode : 0644;
  3502. debugfs_create_file(p->name, mode, kvm_debugfs_dir,
  3503. (void *)(long)p->offset,
  3504. stat_fops[p->kind]);
  3505. }
  3506. }
  3507. static int kvm_suspend(void)
  3508. {
  3509. if (kvm_usage_count)
  3510. hardware_disable_nolock(NULL);
  3511. return 0;
  3512. }
  3513. static void kvm_resume(void)
  3514. {
  3515. if (kvm_usage_count) {
  3516. WARN_ON(raw_spin_is_locked(&kvm_count_lock));
  3517. hardware_enable_nolock(NULL);
  3518. }
  3519. }
  3520. static struct syscore_ops kvm_syscore_ops = {
  3521. .suspend = kvm_suspend,
  3522. .resume = kvm_resume,
  3523. };
  3524. static inline
  3525. struct kvm_vcpu *preempt_notifier_to_vcpu(struct preempt_notifier *pn)
  3526. {
  3527. return container_of(pn, struct kvm_vcpu, preempt_notifier);
  3528. }
  3529. static void kvm_sched_in(struct preempt_notifier *pn, int cpu)
  3530. {
  3531. struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
  3532. if (vcpu->preempted)
  3533. vcpu->preempted = false;
  3534. kvm_arch_sched_in(vcpu, cpu);
  3535. kvm_arch_vcpu_load(vcpu, cpu);
  3536. }
  3537. static void kvm_sched_out(struct preempt_notifier *pn,
  3538. struct task_struct *next)
  3539. {
  3540. struct kvm_vcpu *vcpu = preempt_notifier_to_vcpu(pn);
  3541. if (current->state == TASK_RUNNING)
  3542. vcpu->preempted = true;
  3543. kvm_arch_vcpu_put(vcpu);
  3544. }
  3545. int kvm_init(void *opaque, unsigned vcpu_size, unsigned vcpu_align,
  3546. struct module *module)
  3547. {
  3548. int r;
  3549. int cpu;
  3550. r = kvm_arch_init(opaque);
  3551. if (r)
  3552. goto out_fail;
  3553. /*
  3554. * kvm_arch_init makes sure there's at most one caller
  3555. * for architectures that support multiple implementations,
  3556. * like intel and amd on x86.
  3557. * kvm_arch_init must be called before kvm_irqfd_init to avoid creating
  3558. * conflicts in case kvm is already setup for another implementation.
  3559. */
  3560. r = kvm_irqfd_init();
  3561. if (r)
  3562. goto out_irqfd;
  3563. if (!zalloc_cpumask_var(&cpus_hardware_enabled, GFP_KERNEL)) {
  3564. r = -ENOMEM;
  3565. goto out_free_0;
  3566. }
  3567. r = kvm_arch_hardware_setup();
  3568. if (r < 0)
  3569. goto out_free_0a;
  3570. for_each_online_cpu(cpu) {
  3571. smp_call_function_single(cpu,
  3572. kvm_arch_check_processor_compat,
  3573. &r, 1);
  3574. if (r < 0)
  3575. goto out_free_1;
  3576. }
  3577. r = cpuhp_setup_state_nocalls(CPUHP_AP_KVM_STARTING, "kvm/cpu:starting",
  3578. kvm_starting_cpu, kvm_dying_cpu);
  3579. if (r)
  3580. goto out_free_2;
  3581. register_reboot_notifier(&kvm_reboot_notifier);
  3582. /* A kmem cache lets us meet the alignment requirements of fx_save. */
  3583. if (!vcpu_align)
  3584. vcpu_align = __alignof__(struct kvm_vcpu);
  3585. kvm_vcpu_cache =
  3586. kmem_cache_create_usercopy("kvm_vcpu", vcpu_size, vcpu_align,
  3587. SLAB_ACCOUNT,
  3588. offsetof(struct kvm_vcpu, arch),
  3589. sizeof_field(struct kvm_vcpu, arch),
  3590. NULL);
  3591. if (!kvm_vcpu_cache) {
  3592. r = -ENOMEM;
  3593. goto out_free_3;
  3594. }
  3595. r = kvm_async_pf_init();
  3596. if (r)
  3597. goto out_free;
  3598. kvm_chardev_ops.owner = module;
  3599. kvm_vm_fops.owner = module;
  3600. kvm_vcpu_fops.owner = module;
  3601. r = misc_register(&kvm_dev);
  3602. if (r) {
  3603. pr_err("kvm: misc device register failed\n");
  3604. goto out_unreg;
  3605. }
  3606. register_syscore_ops(&kvm_syscore_ops);
  3607. kvm_preempt_ops.sched_in = kvm_sched_in;
  3608. kvm_preempt_ops.sched_out = kvm_sched_out;
  3609. kvm_init_debug();
  3610. r = kvm_vfio_ops_init();
  3611. WARN_ON(r);
  3612. return 0;
  3613. out_unreg:
  3614. kvm_async_pf_deinit();
  3615. out_free:
  3616. kmem_cache_destroy(kvm_vcpu_cache);
  3617. out_free_3:
  3618. unregister_reboot_notifier(&kvm_reboot_notifier);
  3619. cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
  3620. out_free_2:
  3621. out_free_1:
  3622. kvm_arch_hardware_unsetup();
  3623. out_free_0a:
  3624. free_cpumask_var(cpus_hardware_enabled);
  3625. out_free_0:
  3626. kvm_irqfd_exit();
  3627. out_irqfd:
  3628. kvm_arch_exit();
  3629. out_fail:
  3630. return r;
  3631. }
  3632. EXPORT_SYMBOL_GPL(kvm_init);
  3633. void kvm_exit(void)
  3634. {
  3635. debugfs_remove_recursive(kvm_debugfs_dir);
  3636. misc_deregister(&kvm_dev);
  3637. kmem_cache_destroy(kvm_vcpu_cache);
  3638. kvm_async_pf_deinit();
  3639. unregister_syscore_ops(&kvm_syscore_ops);
  3640. unregister_reboot_notifier(&kvm_reboot_notifier);
  3641. cpuhp_remove_state_nocalls(CPUHP_AP_KVM_STARTING);
  3642. on_each_cpu(hardware_disable_nolock, NULL, 1);
  3643. kvm_arch_hardware_unsetup();
  3644. kvm_arch_exit();
  3645. kvm_irqfd_exit();
  3646. free_cpumask_var(cpus_hardware_enabled);
  3647. kvm_vfio_ops_exit();
  3648. }
  3649. EXPORT_SYMBOL_GPL(kvm_exit);
  3650. struct kvm_vm_worker_thread_context {
  3651. struct kvm *kvm;
  3652. struct task_struct *parent;
  3653. struct completion init_done;
  3654. kvm_vm_thread_fn_t thread_fn;
  3655. uintptr_t data;
  3656. int err;
  3657. };
  3658. static int kvm_vm_worker_thread(void *context)
  3659. {
  3660. /*
  3661. * The init_context is allocated on the stack of the parent thread, so
  3662. * we have to locally copy anything that is needed beyond initialization
  3663. */
  3664. struct kvm_vm_worker_thread_context *init_context = context;
  3665. struct kvm *kvm = init_context->kvm;
  3666. kvm_vm_thread_fn_t thread_fn = init_context->thread_fn;
  3667. uintptr_t data = init_context->data;
  3668. int err;
  3669. err = kthread_park(current);
  3670. /* kthread_park(current) is never supposed to return an error */
  3671. WARN_ON(err != 0);
  3672. if (err)
  3673. goto init_complete;
  3674. err = cgroup_attach_task_all(init_context->parent, current);
  3675. if (err) {
  3676. kvm_err("%s: cgroup_attach_task_all failed with err %d\n",
  3677. __func__, err);
  3678. goto init_complete;
  3679. }
  3680. set_user_nice(current, task_nice(init_context->parent));
  3681. init_complete:
  3682. init_context->err = err;
  3683. complete(&init_context->init_done);
  3684. init_context = NULL;
  3685. if (err)
  3686. return err;
  3687. /* Wait to be woken up by the spawner before proceeding. */
  3688. kthread_parkme();
  3689. if (!kthread_should_stop())
  3690. err = thread_fn(kvm, data);
  3691. return err;
  3692. }
  3693. int kvm_vm_create_worker_thread(struct kvm *kvm, kvm_vm_thread_fn_t thread_fn,
  3694. uintptr_t data, const char *name,
  3695. struct task_struct **thread_ptr)
  3696. {
  3697. struct kvm_vm_worker_thread_context init_context = {};
  3698. struct task_struct *thread;
  3699. *thread_ptr = NULL;
  3700. init_context.kvm = kvm;
  3701. init_context.parent = current;
  3702. init_context.thread_fn = thread_fn;
  3703. init_context.data = data;
  3704. init_completion(&init_context.init_done);
  3705. thread = kthread_run(kvm_vm_worker_thread, &init_context,
  3706. "%s-%d", name, task_pid_nr(current));
  3707. if (IS_ERR(thread))
  3708. return PTR_ERR(thread);
  3709. /* kthread_run is never supposed to return NULL */
  3710. WARN_ON(thread == NULL);
  3711. wait_for_completion(&init_context.init_done);
  3712. if (!init_context.err)
  3713. *thread_ptr = thread;
  3714. return init_context.err;
  3715. }