kvm_main.c 100 KB

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