kvm_main.c 95 KB

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