kvm_main.c 96 KB

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