kvm_main.c 96 KB

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