kvm_main.c 96 KB

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