kvm_main.c 95 KB

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