kvm_main.c 94 KB

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