kvm_main.c 94 KB

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