kvm_main.c 94 KB

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