kvm_main.c 96 KB

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