kvm_main.c 96 KB

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