kvm_main.c 95 KB

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