kvm_main.c 94 KB

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