kvm-all.c 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448
  1. /*
  2. * QEMU KVM support
  3. *
  4. * Copyright IBM, Corp. 2008
  5. * Red Hat, Inc. 2008
  6. *
  7. * Authors:
  8. * Anthony Liguori <aliguori@us.ibm.com>
  9. * Glauber Costa <gcosta@redhat.com>
  10. *
  11. * This work is licensed under the terms of the GNU GPL, version 2 or later.
  12. * See the COPYING file in the top-level directory.
  13. *
  14. */
  15. #include "qemu/osdep.h"
  16. #include <sys/ioctl.h>
  17. #include <poll.h>
  18. #include <linux/kvm.h>
  19. #include "qemu/atomic.h"
  20. #include "qemu/option.h"
  21. #include "qemu/config-file.h"
  22. #include "qemu/error-report.h"
  23. #include "qapi/error.h"
  24. #include "hw/pci/msi.h"
  25. #include "hw/pci/msix.h"
  26. #include "hw/s390x/adapter.h"
  27. #include "gdbstub/enums.h"
  28. #include "system/kvm_int.h"
  29. #include "system/runstate.h"
  30. #include "system/cpus.h"
  31. #include "system/accel-blocker.h"
  32. #include "qemu/bswap.h"
  33. #include "exec/memory.h"
  34. #include "exec/ram_addr.h"
  35. #include "qemu/event_notifier.h"
  36. #include "qemu/main-loop.h"
  37. #include "trace.h"
  38. #include "hw/irq.h"
  39. #include "qapi/visitor.h"
  40. #include "qapi/qapi-types-common.h"
  41. #include "qapi/qapi-visit-common.h"
  42. #include "system/reset.h"
  43. #include "qemu/guest-random.h"
  44. #include "system/hw_accel.h"
  45. #include "kvm-cpus.h"
  46. #include "system/dirtylimit.h"
  47. #include "qemu/range.h"
  48. #include "hw/boards.h"
  49. #include "system/stats.h"
  50. /* This check must be after config-host.h is included */
  51. #ifdef CONFIG_EVENTFD
  52. #include <sys/eventfd.h>
  53. #endif
  54. /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
  55. * need to use the real host PAGE_SIZE, as that's what KVM will use.
  56. */
  57. #ifdef PAGE_SIZE
  58. #undef PAGE_SIZE
  59. #endif
  60. #define PAGE_SIZE qemu_real_host_page_size()
  61. #ifndef KVM_GUESTDBG_BLOCKIRQ
  62. #define KVM_GUESTDBG_BLOCKIRQ 0
  63. #endif
  64. /* Default num of memslots to be allocated when VM starts */
  65. #define KVM_MEMSLOTS_NR_ALLOC_DEFAULT 16
  66. /* Default max allowed memslots if kernel reported nothing */
  67. #define KVM_MEMSLOTS_NR_MAX_DEFAULT 32
  68. struct KVMParkedVcpu {
  69. unsigned long vcpu_id;
  70. int kvm_fd;
  71. QLIST_ENTRY(KVMParkedVcpu) node;
  72. };
  73. KVMState *kvm_state;
  74. bool kvm_kernel_irqchip;
  75. bool kvm_split_irqchip;
  76. bool kvm_async_interrupts_allowed;
  77. bool kvm_halt_in_kernel_allowed;
  78. bool kvm_resamplefds_allowed;
  79. bool kvm_msi_via_irqfd_allowed;
  80. bool kvm_gsi_routing_allowed;
  81. bool kvm_gsi_direct_mapping;
  82. bool kvm_allowed;
  83. bool kvm_readonly_mem_allowed;
  84. bool kvm_vm_attributes_allowed;
  85. bool kvm_msi_use_devid;
  86. static bool kvm_has_guest_debug;
  87. static int kvm_sstep_flags;
  88. static bool kvm_immediate_exit;
  89. static uint64_t kvm_supported_memory_attributes;
  90. static bool kvm_guest_memfd_supported;
  91. static hwaddr kvm_max_slot_size = ~0;
  92. static const KVMCapabilityInfo kvm_required_capabilites[] = {
  93. KVM_CAP_INFO(USER_MEMORY),
  94. KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
  95. KVM_CAP_INFO(JOIN_MEMORY_REGIONS_WORKS),
  96. KVM_CAP_INFO(INTERNAL_ERROR_DATA),
  97. KVM_CAP_INFO(IOEVENTFD),
  98. KVM_CAP_INFO(IOEVENTFD_ANY_LENGTH),
  99. KVM_CAP_LAST_INFO
  100. };
  101. static NotifierList kvm_irqchip_change_notifiers =
  102. NOTIFIER_LIST_INITIALIZER(kvm_irqchip_change_notifiers);
  103. struct KVMResampleFd {
  104. int gsi;
  105. EventNotifier *resample_event;
  106. QLIST_ENTRY(KVMResampleFd) node;
  107. };
  108. typedef struct KVMResampleFd KVMResampleFd;
  109. /*
  110. * Only used with split irqchip where we need to do the resample fd
  111. * kick for the kernel from userspace.
  112. */
  113. static QLIST_HEAD(, KVMResampleFd) kvm_resample_fd_list =
  114. QLIST_HEAD_INITIALIZER(kvm_resample_fd_list);
  115. static QemuMutex kml_slots_lock;
  116. #define kvm_slots_lock() qemu_mutex_lock(&kml_slots_lock)
  117. #define kvm_slots_unlock() qemu_mutex_unlock(&kml_slots_lock)
  118. static void kvm_slot_init_dirty_bitmap(KVMSlot *mem);
  119. static inline void kvm_resample_fd_remove(int gsi)
  120. {
  121. KVMResampleFd *rfd;
  122. QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
  123. if (rfd->gsi == gsi) {
  124. QLIST_REMOVE(rfd, node);
  125. g_free(rfd);
  126. break;
  127. }
  128. }
  129. }
  130. static inline void kvm_resample_fd_insert(int gsi, EventNotifier *event)
  131. {
  132. KVMResampleFd *rfd = g_new0(KVMResampleFd, 1);
  133. rfd->gsi = gsi;
  134. rfd->resample_event = event;
  135. QLIST_INSERT_HEAD(&kvm_resample_fd_list, rfd, node);
  136. }
  137. void kvm_resample_fd_notify(int gsi)
  138. {
  139. KVMResampleFd *rfd;
  140. QLIST_FOREACH(rfd, &kvm_resample_fd_list, node) {
  141. if (rfd->gsi == gsi) {
  142. event_notifier_set(rfd->resample_event);
  143. trace_kvm_resample_fd_notify(gsi);
  144. return;
  145. }
  146. }
  147. }
  148. /**
  149. * kvm_slots_grow(): Grow the slots[] array in the KVMMemoryListener
  150. *
  151. * @kml: The KVMMemoryListener* to grow the slots[] array
  152. * @nr_slots_new: The new size of slots[] array
  153. *
  154. * Returns: True if the array grows larger, false otherwise.
  155. */
  156. static bool kvm_slots_grow(KVMMemoryListener *kml, unsigned int nr_slots_new)
  157. {
  158. unsigned int i, cur = kml->nr_slots_allocated;
  159. KVMSlot *slots;
  160. if (nr_slots_new > kvm_state->nr_slots_max) {
  161. nr_slots_new = kvm_state->nr_slots_max;
  162. }
  163. if (cur >= nr_slots_new) {
  164. /* Big enough, no need to grow, or we reached max */
  165. return false;
  166. }
  167. if (cur == 0) {
  168. slots = g_new0(KVMSlot, nr_slots_new);
  169. } else {
  170. assert(kml->slots);
  171. slots = g_renew(KVMSlot, kml->slots, nr_slots_new);
  172. /*
  173. * g_renew() doesn't initialize extended buffers, however kvm
  174. * memslots require fields to be zero-initialized. E.g. pointers,
  175. * memory_size field, etc.
  176. */
  177. memset(&slots[cur], 0x0, sizeof(slots[0]) * (nr_slots_new - cur));
  178. }
  179. for (i = cur; i < nr_slots_new; i++) {
  180. slots[i].slot = i;
  181. }
  182. kml->slots = slots;
  183. kml->nr_slots_allocated = nr_slots_new;
  184. trace_kvm_slots_grow(cur, nr_slots_new);
  185. return true;
  186. }
  187. static bool kvm_slots_double(KVMMemoryListener *kml)
  188. {
  189. return kvm_slots_grow(kml, kml->nr_slots_allocated * 2);
  190. }
  191. unsigned int kvm_get_max_memslots(void)
  192. {
  193. KVMState *s = KVM_STATE(current_accel());
  194. return s->nr_slots_max;
  195. }
  196. unsigned int kvm_get_free_memslots(void)
  197. {
  198. unsigned int used_slots = 0;
  199. KVMState *s = kvm_state;
  200. int i;
  201. kvm_slots_lock();
  202. for (i = 0; i < s->nr_as; i++) {
  203. if (!s->as[i].ml) {
  204. continue;
  205. }
  206. used_slots = MAX(used_slots, s->as[i].ml->nr_slots_used);
  207. }
  208. kvm_slots_unlock();
  209. return s->nr_slots_max - used_slots;
  210. }
  211. /* Called with KVMMemoryListener.slots_lock held */
  212. static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
  213. {
  214. unsigned int n;
  215. int i;
  216. for (i = 0; i < kml->nr_slots_allocated; i++) {
  217. if (kml->slots[i].memory_size == 0) {
  218. return &kml->slots[i];
  219. }
  220. }
  221. /*
  222. * If no free slots, try to grow first by doubling. Cache the old size
  223. * here to avoid another round of search: if the grow succeeded, it
  224. * means slots[] now must have the existing "n" slots occupied,
  225. * followed by one or more free slots starting from slots[n].
  226. */
  227. n = kml->nr_slots_allocated;
  228. if (kvm_slots_double(kml)) {
  229. return &kml->slots[n];
  230. }
  231. return NULL;
  232. }
  233. /* Called with KVMMemoryListener.slots_lock held */
  234. static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
  235. {
  236. KVMSlot *slot = kvm_get_free_slot(kml);
  237. if (slot) {
  238. return slot;
  239. }
  240. fprintf(stderr, "%s: no free slot available\n", __func__);
  241. abort();
  242. }
  243. static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
  244. hwaddr start_addr,
  245. hwaddr size)
  246. {
  247. int i;
  248. for (i = 0; i < kml->nr_slots_allocated; i++) {
  249. KVMSlot *mem = &kml->slots[i];
  250. if (start_addr == mem->start_addr && size == mem->memory_size) {
  251. return mem;
  252. }
  253. }
  254. return NULL;
  255. }
  256. /*
  257. * Calculate and align the start address and the size of the section.
  258. * Return the size. If the size is 0, the aligned section is empty.
  259. */
  260. static hwaddr kvm_align_section(MemoryRegionSection *section,
  261. hwaddr *start)
  262. {
  263. hwaddr size = int128_get64(section->size);
  264. hwaddr delta, aligned;
  265. /* kvm works in page size chunks, but the function may be called
  266. with sub-page size and unaligned start address. Pad the start
  267. address to next and truncate size to previous page boundary. */
  268. aligned = ROUND_UP(section->offset_within_address_space,
  269. qemu_real_host_page_size());
  270. delta = aligned - section->offset_within_address_space;
  271. *start = aligned;
  272. if (delta > size) {
  273. return 0;
  274. }
  275. return (size - delta) & qemu_real_host_page_mask();
  276. }
  277. int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
  278. hwaddr *phys_addr)
  279. {
  280. KVMMemoryListener *kml = &s->memory_listener;
  281. int i, ret = 0;
  282. kvm_slots_lock();
  283. for (i = 0; i < kml->nr_slots_allocated; i++) {
  284. KVMSlot *mem = &kml->slots[i];
  285. if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
  286. *phys_addr = mem->start_addr + (ram - mem->ram);
  287. ret = 1;
  288. break;
  289. }
  290. }
  291. kvm_slots_unlock();
  292. return ret;
  293. }
  294. static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot, bool new)
  295. {
  296. KVMState *s = kvm_state;
  297. struct kvm_userspace_memory_region2 mem;
  298. int ret;
  299. mem.slot = slot->slot | (kml->as_id << 16);
  300. mem.guest_phys_addr = slot->start_addr;
  301. mem.userspace_addr = (unsigned long)slot->ram;
  302. mem.flags = slot->flags;
  303. mem.guest_memfd = slot->guest_memfd;
  304. mem.guest_memfd_offset = slot->guest_memfd_offset;
  305. if (slot->memory_size && !new && (mem.flags ^ slot->old_flags) & KVM_MEM_READONLY) {
  306. /* Set the slot size to 0 before setting the slot to the desired
  307. * value. This is needed based on KVM commit 75d61fbc. */
  308. mem.memory_size = 0;
  309. if (kvm_guest_memfd_supported) {
  310. ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION2, &mem);
  311. } else {
  312. ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
  313. }
  314. if (ret < 0) {
  315. goto err;
  316. }
  317. }
  318. mem.memory_size = slot->memory_size;
  319. if (kvm_guest_memfd_supported) {
  320. ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION2, &mem);
  321. } else {
  322. ret = kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
  323. }
  324. slot->old_flags = mem.flags;
  325. err:
  326. trace_kvm_set_user_memory(mem.slot >> 16, (uint16_t)mem.slot, mem.flags,
  327. mem.guest_phys_addr, mem.memory_size,
  328. mem.userspace_addr, mem.guest_memfd,
  329. mem.guest_memfd_offset, ret);
  330. if (ret < 0) {
  331. if (kvm_guest_memfd_supported) {
  332. error_report("%s: KVM_SET_USER_MEMORY_REGION2 failed, slot=%d,"
  333. " start=0x%" PRIx64 ", size=0x%" PRIx64 ","
  334. " flags=0x%" PRIx32 ", guest_memfd=%" PRId32 ","
  335. " guest_memfd_offset=0x%" PRIx64 ": %s",
  336. __func__, mem.slot, slot->start_addr,
  337. (uint64_t)mem.memory_size, mem.flags,
  338. mem.guest_memfd, (uint64_t)mem.guest_memfd_offset,
  339. strerror(errno));
  340. } else {
  341. error_report("%s: KVM_SET_USER_MEMORY_REGION failed, slot=%d,"
  342. " start=0x%" PRIx64 ", size=0x%" PRIx64 ": %s",
  343. __func__, mem.slot, slot->start_addr,
  344. (uint64_t)mem.memory_size, strerror(errno));
  345. }
  346. }
  347. return ret;
  348. }
  349. void kvm_park_vcpu(CPUState *cpu)
  350. {
  351. struct KVMParkedVcpu *vcpu;
  352. trace_kvm_park_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
  353. vcpu = g_malloc0(sizeof(*vcpu));
  354. vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
  355. vcpu->kvm_fd = cpu->kvm_fd;
  356. QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
  357. }
  358. int kvm_unpark_vcpu(KVMState *s, unsigned long vcpu_id)
  359. {
  360. struct KVMParkedVcpu *cpu;
  361. int kvm_fd = -ENOENT;
  362. QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
  363. if (cpu->vcpu_id == vcpu_id) {
  364. QLIST_REMOVE(cpu, node);
  365. kvm_fd = cpu->kvm_fd;
  366. g_free(cpu);
  367. break;
  368. }
  369. }
  370. trace_kvm_unpark_vcpu(vcpu_id, kvm_fd > 0 ? "unparked" : "!found parked");
  371. return kvm_fd;
  372. }
  373. static void kvm_reset_parked_vcpus(KVMState *s)
  374. {
  375. struct KVMParkedVcpu *cpu;
  376. QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
  377. kvm_arch_reset_parked_vcpu(cpu->vcpu_id, cpu->kvm_fd);
  378. }
  379. }
  380. int kvm_create_vcpu(CPUState *cpu)
  381. {
  382. unsigned long vcpu_id = kvm_arch_vcpu_id(cpu);
  383. KVMState *s = kvm_state;
  384. int kvm_fd;
  385. /* check if the KVM vCPU already exist but is parked */
  386. kvm_fd = kvm_unpark_vcpu(s, vcpu_id);
  387. if (kvm_fd < 0) {
  388. /* vCPU not parked: create a new KVM vCPU */
  389. kvm_fd = kvm_vm_ioctl(s, KVM_CREATE_VCPU, vcpu_id);
  390. if (kvm_fd < 0) {
  391. error_report("KVM_CREATE_VCPU IOCTL failed for vCPU %lu", vcpu_id);
  392. return kvm_fd;
  393. }
  394. }
  395. cpu->kvm_fd = kvm_fd;
  396. cpu->kvm_state = s;
  397. cpu->vcpu_dirty = true;
  398. cpu->dirty_pages = 0;
  399. cpu->throttle_us_per_full = 0;
  400. trace_kvm_create_vcpu(cpu->cpu_index, vcpu_id, kvm_fd);
  401. return 0;
  402. }
  403. int kvm_create_and_park_vcpu(CPUState *cpu)
  404. {
  405. int ret = 0;
  406. ret = kvm_create_vcpu(cpu);
  407. if (!ret) {
  408. kvm_park_vcpu(cpu);
  409. }
  410. return ret;
  411. }
  412. static int do_kvm_destroy_vcpu(CPUState *cpu)
  413. {
  414. KVMState *s = kvm_state;
  415. int mmap_size;
  416. int ret = 0;
  417. trace_kvm_destroy_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
  418. ret = kvm_arch_destroy_vcpu(cpu);
  419. if (ret < 0) {
  420. goto err;
  421. }
  422. mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
  423. if (mmap_size < 0) {
  424. ret = mmap_size;
  425. trace_kvm_failed_get_vcpu_mmap_size();
  426. goto err;
  427. }
  428. ret = munmap(cpu->kvm_run, mmap_size);
  429. if (ret < 0) {
  430. goto err;
  431. }
  432. if (cpu->kvm_dirty_gfns) {
  433. ret = munmap(cpu->kvm_dirty_gfns, s->kvm_dirty_ring_bytes);
  434. if (ret < 0) {
  435. goto err;
  436. }
  437. }
  438. kvm_park_vcpu(cpu);
  439. err:
  440. return ret;
  441. }
  442. void kvm_destroy_vcpu(CPUState *cpu)
  443. {
  444. if (do_kvm_destroy_vcpu(cpu) < 0) {
  445. error_report("kvm_destroy_vcpu failed");
  446. exit(EXIT_FAILURE);
  447. }
  448. }
  449. int kvm_init_vcpu(CPUState *cpu, Error **errp)
  450. {
  451. KVMState *s = kvm_state;
  452. int mmap_size;
  453. int ret;
  454. trace_kvm_init_vcpu(cpu->cpu_index, kvm_arch_vcpu_id(cpu));
  455. ret = kvm_create_vcpu(cpu);
  456. if (ret < 0) {
  457. error_setg_errno(errp, -ret,
  458. "kvm_init_vcpu: kvm_create_vcpu failed (%lu)",
  459. kvm_arch_vcpu_id(cpu));
  460. goto err;
  461. }
  462. mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
  463. if (mmap_size < 0) {
  464. ret = mmap_size;
  465. error_setg_errno(errp, -mmap_size,
  466. "kvm_init_vcpu: KVM_GET_VCPU_MMAP_SIZE failed");
  467. goto err;
  468. }
  469. cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
  470. cpu->kvm_fd, 0);
  471. if (cpu->kvm_run == MAP_FAILED) {
  472. ret = -errno;
  473. error_setg_errno(errp, ret,
  474. "kvm_init_vcpu: mmap'ing vcpu state failed (%lu)",
  475. kvm_arch_vcpu_id(cpu));
  476. goto err;
  477. }
  478. if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
  479. s->coalesced_mmio_ring =
  480. (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
  481. }
  482. if (s->kvm_dirty_ring_size) {
  483. /* Use MAP_SHARED to share pages with the kernel */
  484. cpu->kvm_dirty_gfns = mmap(NULL, s->kvm_dirty_ring_bytes,
  485. PROT_READ | PROT_WRITE, MAP_SHARED,
  486. cpu->kvm_fd,
  487. PAGE_SIZE * KVM_DIRTY_LOG_PAGE_OFFSET);
  488. if (cpu->kvm_dirty_gfns == MAP_FAILED) {
  489. ret = -errno;
  490. goto err;
  491. }
  492. }
  493. ret = kvm_arch_init_vcpu(cpu);
  494. if (ret < 0) {
  495. error_setg_errno(errp, -ret,
  496. "kvm_init_vcpu: kvm_arch_init_vcpu failed (%lu)",
  497. kvm_arch_vcpu_id(cpu));
  498. }
  499. cpu->kvm_vcpu_stats_fd = kvm_vcpu_ioctl(cpu, KVM_GET_STATS_FD, NULL);
  500. err:
  501. return ret;
  502. }
  503. /*
  504. * dirty pages logging control
  505. */
  506. static int kvm_mem_flags(MemoryRegion *mr)
  507. {
  508. bool readonly = mr->readonly || memory_region_is_romd(mr);
  509. int flags = 0;
  510. if (memory_region_get_dirty_log_mask(mr) != 0) {
  511. flags |= KVM_MEM_LOG_DIRTY_PAGES;
  512. }
  513. if (readonly && kvm_readonly_mem_allowed) {
  514. flags |= KVM_MEM_READONLY;
  515. }
  516. if (memory_region_has_guest_memfd(mr)) {
  517. assert(kvm_guest_memfd_supported);
  518. flags |= KVM_MEM_GUEST_MEMFD;
  519. }
  520. return flags;
  521. }
  522. /* Called with KVMMemoryListener.slots_lock held */
  523. static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
  524. MemoryRegion *mr)
  525. {
  526. mem->flags = kvm_mem_flags(mr);
  527. /* If nothing changed effectively, no need to issue ioctl */
  528. if (mem->flags == mem->old_flags) {
  529. return 0;
  530. }
  531. kvm_slot_init_dirty_bitmap(mem);
  532. return kvm_set_user_memory_region(kml, mem, false);
  533. }
  534. static int kvm_section_update_flags(KVMMemoryListener *kml,
  535. MemoryRegionSection *section)
  536. {
  537. hwaddr start_addr, size, slot_size;
  538. KVMSlot *mem;
  539. int ret = 0;
  540. size = kvm_align_section(section, &start_addr);
  541. if (!size) {
  542. return 0;
  543. }
  544. kvm_slots_lock();
  545. while (size && !ret) {
  546. slot_size = MIN(kvm_max_slot_size, size);
  547. mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
  548. if (!mem) {
  549. /* We don't have a slot if we want to trap every access. */
  550. goto out;
  551. }
  552. ret = kvm_slot_update_flags(kml, mem, section->mr);
  553. start_addr += slot_size;
  554. size -= slot_size;
  555. }
  556. out:
  557. kvm_slots_unlock();
  558. return ret;
  559. }
  560. static void kvm_log_start(MemoryListener *listener,
  561. MemoryRegionSection *section,
  562. int old, int new)
  563. {
  564. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  565. int r;
  566. if (old != 0) {
  567. return;
  568. }
  569. r = kvm_section_update_flags(kml, section);
  570. if (r < 0) {
  571. abort();
  572. }
  573. }
  574. static void kvm_log_stop(MemoryListener *listener,
  575. MemoryRegionSection *section,
  576. int old, int new)
  577. {
  578. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  579. int r;
  580. if (new != 0) {
  581. return;
  582. }
  583. r = kvm_section_update_flags(kml, section);
  584. if (r < 0) {
  585. abort();
  586. }
  587. }
  588. /* get kvm's dirty pages bitmap and update qemu's */
  589. static void kvm_slot_sync_dirty_pages(KVMSlot *slot)
  590. {
  591. ram_addr_t start = slot->ram_start_offset;
  592. ram_addr_t pages = slot->memory_size / qemu_real_host_page_size();
  593. cpu_physical_memory_set_dirty_lebitmap(slot->dirty_bmap, start, pages);
  594. }
  595. static void kvm_slot_reset_dirty_pages(KVMSlot *slot)
  596. {
  597. memset(slot->dirty_bmap, 0, slot->dirty_bmap_size);
  598. }
  599. #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
  600. /* Allocate the dirty bitmap for a slot */
  601. static void kvm_slot_init_dirty_bitmap(KVMSlot *mem)
  602. {
  603. if (!(mem->flags & KVM_MEM_LOG_DIRTY_PAGES) || mem->dirty_bmap) {
  604. return;
  605. }
  606. /*
  607. * XXX bad kernel interface alert
  608. * For dirty bitmap, kernel allocates array of size aligned to
  609. * bits-per-long. But for case when the kernel is 64bits and
  610. * the userspace is 32bits, userspace can't align to the same
  611. * bits-per-long, since sizeof(long) is different between kernel
  612. * and user space. This way, userspace will provide buffer which
  613. * may be 4 bytes less than the kernel will use, resulting in
  614. * userspace memory corruption (which is not detectable by valgrind
  615. * too, in most cases).
  616. * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
  617. * a hope that sizeof(long) won't become >8 any time soon.
  618. *
  619. * Note: the granule of kvm dirty log is qemu_real_host_page_size.
  620. * And mem->memory_size is aligned to it (otherwise this mem can't
  621. * be registered to KVM).
  622. */
  623. hwaddr bitmap_size = ALIGN(mem->memory_size / qemu_real_host_page_size(),
  624. /*HOST_LONG_BITS*/ 64) / 8;
  625. mem->dirty_bmap = g_malloc0(bitmap_size);
  626. mem->dirty_bmap_size = bitmap_size;
  627. }
  628. /*
  629. * Sync dirty bitmap from kernel to KVMSlot.dirty_bmap, return true if
  630. * succeeded, false otherwise
  631. */
  632. static bool kvm_slot_get_dirty_log(KVMState *s, KVMSlot *slot)
  633. {
  634. struct kvm_dirty_log d = {};
  635. int ret;
  636. d.dirty_bitmap = slot->dirty_bmap;
  637. d.slot = slot->slot | (slot->as_id << 16);
  638. ret = kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d);
  639. if (ret == -ENOENT) {
  640. /* kernel does not have dirty bitmap in this slot */
  641. ret = 0;
  642. }
  643. if (ret) {
  644. error_report_once("%s: KVM_GET_DIRTY_LOG failed with %d",
  645. __func__, ret);
  646. }
  647. return ret == 0;
  648. }
  649. /* Should be with all slots_lock held for the address spaces. */
  650. static void kvm_dirty_ring_mark_page(KVMState *s, uint32_t as_id,
  651. uint32_t slot_id, uint64_t offset)
  652. {
  653. KVMMemoryListener *kml;
  654. KVMSlot *mem;
  655. if (as_id >= s->nr_as) {
  656. return;
  657. }
  658. kml = s->as[as_id].ml;
  659. mem = &kml->slots[slot_id];
  660. if (!mem->memory_size || offset >=
  661. (mem->memory_size / qemu_real_host_page_size())) {
  662. return;
  663. }
  664. set_bit(offset, mem->dirty_bmap);
  665. }
  666. static bool dirty_gfn_is_dirtied(struct kvm_dirty_gfn *gfn)
  667. {
  668. /*
  669. * Read the flags before the value. Pairs with barrier in
  670. * KVM's kvm_dirty_ring_push() function.
  671. */
  672. return qatomic_load_acquire(&gfn->flags) == KVM_DIRTY_GFN_F_DIRTY;
  673. }
  674. static void dirty_gfn_set_collected(struct kvm_dirty_gfn *gfn)
  675. {
  676. /*
  677. * Use a store-release so that the CPU that executes KVM_RESET_DIRTY_RINGS
  678. * sees the full content of the ring:
  679. *
  680. * CPU0 CPU1 CPU2
  681. * ------------------------------------------------------------------------------
  682. * fill gfn0
  683. * store-rel flags for gfn0
  684. * load-acq flags for gfn0
  685. * store-rel RESET for gfn0
  686. * ioctl(RESET_RINGS)
  687. * load-acq flags for gfn0
  688. * check if flags have RESET
  689. *
  690. * The synchronization goes from CPU2 to CPU0 to CPU1.
  691. */
  692. qatomic_store_release(&gfn->flags, KVM_DIRTY_GFN_F_RESET);
  693. }
  694. /*
  695. * Should be with all slots_lock held for the address spaces. It returns the
  696. * dirty page we've collected on this dirty ring.
  697. */
  698. static uint32_t kvm_dirty_ring_reap_one(KVMState *s, CPUState *cpu)
  699. {
  700. struct kvm_dirty_gfn *dirty_gfns = cpu->kvm_dirty_gfns, *cur;
  701. uint32_t ring_size = s->kvm_dirty_ring_size;
  702. uint32_t count = 0, fetch = cpu->kvm_fetch_index;
  703. /*
  704. * It's possible that we race with vcpu creation code where the vcpu is
  705. * put onto the vcpus list but not yet initialized the dirty ring
  706. * structures. If so, skip it.
  707. */
  708. if (!cpu->created) {
  709. return 0;
  710. }
  711. assert(dirty_gfns && ring_size);
  712. trace_kvm_dirty_ring_reap_vcpu(cpu->cpu_index);
  713. while (true) {
  714. cur = &dirty_gfns[fetch % ring_size];
  715. if (!dirty_gfn_is_dirtied(cur)) {
  716. break;
  717. }
  718. kvm_dirty_ring_mark_page(s, cur->slot >> 16, cur->slot & 0xffff,
  719. cur->offset);
  720. dirty_gfn_set_collected(cur);
  721. trace_kvm_dirty_ring_page(cpu->cpu_index, fetch, cur->offset);
  722. fetch++;
  723. count++;
  724. }
  725. cpu->kvm_fetch_index = fetch;
  726. cpu->dirty_pages += count;
  727. return count;
  728. }
  729. /* Must be with slots_lock held */
  730. static uint64_t kvm_dirty_ring_reap_locked(KVMState *s, CPUState* cpu)
  731. {
  732. int ret;
  733. uint64_t total = 0;
  734. int64_t stamp;
  735. stamp = get_clock();
  736. if (cpu) {
  737. total = kvm_dirty_ring_reap_one(s, cpu);
  738. } else {
  739. CPU_FOREACH(cpu) {
  740. total += kvm_dirty_ring_reap_one(s, cpu);
  741. }
  742. }
  743. if (total) {
  744. ret = kvm_vm_ioctl(s, KVM_RESET_DIRTY_RINGS);
  745. assert(ret == total);
  746. }
  747. stamp = get_clock() - stamp;
  748. if (total) {
  749. trace_kvm_dirty_ring_reap(total, stamp / 1000);
  750. }
  751. return total;
  752. }
  753. /*
  754. * Currently for simplicity, we must hold BQL before calling this. We can
  755. * consider to drop the BQL if we're clear with all the race conditions.
  756. */
  757. static uint64_t kvm_dirty_ring_reap(KVMState *s, CPUState *cpu)
  758. {
  759. uint64_t total;
  760. /*
  761. * We need to lock all kvm slots for all address spaces here,
  762. * because:
  763. *
  764. * (1) We need to mark dirty for dirty bitmaps in multiple slots
  765. * and for tons of pages, so it's better to take the lock here
  766. * once rather than once per page. And more importantly,
  767. *
  768. * (2) We must _NOT_ publish dirty bits to the other threads
  769. * (e.g., the migration thread) via the kvm memory slot dirty
  770. * bitmaps before correctly re-protect those dirtied pages.
  771. * Otherwise we can have potential risk of data corruption if
  772. * the page data is read in the other thread before we do
  773. * reset below.
  774. */
  775. kvm_slots_lock();
  776. total = kvm_dirty_ring_reap_locked(s, cpu);
  777. kvm_slots_unlock();
  778. return total;
  779. }
  780. static void do_kvm_cpu_synchronize_kick(CPUState *cpu, run_on_cpu_data arg)
  781. {
  782. /* No need to do anything */
  783. }
  784. /*
  785. * Kick all vcpus out in a synchronized way. When returned, we
  786. * guarantee that every vcpu has been kicked and at least returned to
  787. * userspace once.
  788. */
  789. static void kvm_cpu_synchronize_kick_all(void)
  790. {
  791. CPUState *cpu;
  792. CPU_FOREACH(cpu) {
  793. run_on_cpu(cpu, do_kvm_cpu_synchronize_kick, RUN_ON_CPU_NULL);
  794. }
  795. }
  796. /*
  797. * Flush all the existing dirty pages to the KVM slot buffers. When
  798. * this call returns, we guarantee that all the touched dirty pages
  799. * before calling this function have been put into the per-kvmslot
  800. * dirty bitmap.
  801. *
  802. * This function must be called with BQL held.
  803. */
  804. static void kvm_dirty_ring_flush(void)
  805. {
  806. trace_kvm_dirty_ring_flush(0);
  807. /*
  808. * The function needs to be serialized. Since this function
  809. * should always be with BQL held, serialization is guaranteed.
  810. * However, let's be sure of it.
  811. */
  812. assert(bql_locked());
  813. /*
  814. * First make sure to flush the hardware buffers by kicking all
  815. * vcpus out in a synchronous way.
  816. */
  817. kvm_cpu_synchronize_kick_all();
  818. kvm_dirty_ring_reap(kvm_state, NULL);
  819. trace_kvm_dirty_ring_flush(1);
  820. }
  821. /**
  822. * kvm_physical_sync_dirty_bitmap - Sync dirty bitmap from kernel space
  823. *
  824. * This function will first try to fetch dirty bitmap from the kernel,
  825. * and then updates qemu's dirty bitmap.
  826. *
  827. * NOTE: caller must be with kml->slots_lock held.
  828. *
  829. * @kml: the KVM memory listener object
  830. * @section: the memory section to sync the dirty bitmap with
  831. */
  832. static void kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
  833. MemoryRegionSection *section)
  834. {
  835. KVMState *s = kvm_state;
  836. KVMSlot *mem;
  837. hwaddr start_addr, size;
  838. hwaddr slot_size;
  839. size = kvm_align_section(section, &start_addr);
  840. while (size) {
  841. slot_size = MIN(kvm_max_slot_size, size);
  842. mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
  843. if (!mem) {
  844. /* We don't have a slot if we want to trap every access. */
  845. return;
  846. }
  847. if (kvm_slot_get_dirty_log(s, mem)) {
  848. kvm_slot_sync_dirty_pages(mem);
  849. }
  850. start_addr += slot_size;
  851. size -= slot_size;
  852. }
  853. }
  854. /* Alignment requirement for KVM_CLEAR_DIRTY_LOG - 64 pages */
  855. #define KVM_CLEAR_LOG_SHIFT 6
  856. #define KVM_CLEAR_LOG_ALIGN (qemu_real_host_page_size() << KVM_CLEAR_LOG_SHIFT)
  857. #define KVM_CLEAR_LOG_MASK (-KVM_CLEAR_LOG_ALIGN)
  858. static int kvm_log_clear_one_slot(KVMSlot *mem, int as_id, uint64_t start,
  859. uint64_t size)
  860. {
  861. KVMState *s = kvm_state;
  862. uint64_t end, bmap_start, start_delta, bmap_npages;
  863. struct kvm_clear_dirty_log d;
  864. unsigned long *bmap_clear = NULL, psize = qemu_real_host_page_size();
  865. int ret;
  866. /*
  867. * We need to extend either the start or the size or both to
  868. * satisfy the KVM interface requirement. Firstly, do the start
  869. * page alignment on 64 host pages
  870. */
  871. bmap_start = start & KVM_CLEAR_LOG_MASK;
  872. start_delta = start - bmap_start;
  873. bmap_start /= psize;
  874. /*
  875. * The kernel interface has restriction on the size too, that either:
  876. *
  877. * (1) the size is 64 host pages aligned (just like the start), or
  878. * (2) the size fills up until the end of the KVM memslot.
  879. */
  880. bmap_npages = DIV_ROUND_UP(size + start_delta, KVM_CLEAR_LOG_ALIGN)
  881. << KVM_CLEAR_LOG_SHIFT;
  882. end = mem->memory_size / psize;
  883. if (bmap_npages > end - bmap_start) {
  884. bmap_npages = end - bmap_start;
  885. }
  886. start_delta /= psize;
  887. /*
  888. * Prepare the bitmap to clear dirty bits. Here we must guarantee
  889. * that we won't clear any unknown dirty bits otherwise we might
  890. * accidentally clear some set bits which are not yet synced from
  891. * the kernel into QEMU's bitmap, then we'll lose track of the
  892. * guest modifications upon those pages (which can directly lead
  893. * to guest data loss or panic after migration).
  894. *
  895. * Layout of the KVMSlot.dirty_bmap:
  896. *
  897. * |<-------- bmap_npages -----------..>|
  898. * [1]
  899. * start_delta size
  900. * |----------------|-------------|------------------|------------|
  901. * ^ ^ ^ ^
  902. * | | | |
  903. * start bmap_start (start) end
  904. * of memslot of memslot
  905. *
  906. * [1] bmap_npages can be aligned to either 64 pages or the end of slot
  907. */
  908. assert(bmap_start % BITS_PER_LONG == 0);
  909. /* We should never do log_clear before log_sync */
  910. assert(mem->dirty_bmap);
  911. if (start_delta || bmap_npages - size / psize) {
  912. /* Slow path - we need to manipulate a temp bitmap */
  913. bmap_clear = bitmap_new(bmap_npages);
  914. bitmap_copy_with_src_offset(bmap_clear, mem->dirty_bmap,
  915. bmap_start, start_delta + size / psize);
  916. /*
  917. * We need to fill the holes at start because that was not
  918. * specified by the caller and we extended the bitmap only for
  919. * 64 pages alignment
  920. */
  921. bitmap_clear(bmap_clear, 0, start_delta);
  922. d.dirty_bitmap = bmap_clear;
  923. } else {
  924. /*
  925. * Fast path - both start and size align well with BITS_PER_LONG
  926. * (or the end of memory slot)
  927. */
  928. d.dirty_bitmap = mem->dirty_bmap + BIT_WORD(bmap_start);
  929. }
  930. d.first_page = bmap_start;
  931. /* It should never overflow. If it happens, say something */
  932. assert(bmap_npages <= UINT32_MAX);
  933. d.num_pages = bmap_npages;
  934. d.slot = mem->slot | (as_id << 16);
  935. ret = kvm_vm_ioctl(s, KVM_CLEAR_DIRTY_LOG, &d);
  936. if (ret < 0 && ret != -ENOENT) {
  937. error_report("%s: KVM_CLEAR_DIRTY_LOG failed, slot=%d, "
  938. "start=0x%"PRIx64", size=0x%"PRIx32", errno=%d",
  939. __func__, d.slot, (uint64_t)d.first_page,
  940. (uint32_t)d.num_pages, ret);
  941. } else {
  942. ret = 0;
  943. trace_kvm_clear_dirty_log(d.slot, d.first_page, d.num_pages);
  944. }
  945. /*
  946. * After we have updated the remote dirty bitmap, we update the
  947. * cached bitmap as well for the memslot, then if another user
  948. * clears the same region we know we shouldn't clear it again on
  949. * the remote otherwise it's data loss as well.
  950. */
  951. bitmap_clear(mem->dirty_bmap, bmap_start + start_delta,
  952. size / psize);
  953. /* This handles the NULL case well */
  954. g_free(bmap_clear);
  955. return ret;
  956. }
  957. /**
  958. * kvm_physical_log_clear - Clear the kernel's dirty bitmap for range
  959. *
  960. * NOTE: this will be a no-op if we haven't enabled manual dirty log
  961. * protection in the host kernel because in that case this operation
  962. * will be done within log_sync().
  963. *
  964. * @kml: the kvm memory listener
  965. * @section: the memory range to clear dirty bitmap
  966. */
  967. static int kvm_physical_log_clear(KVMMemoryListener *kml,
  968. MemoryRegionSection *section)
  969. {
  970. KVMState *s = kvm_state;
  971. uint64_t start, size, offset, count;
  972. KVMSlot *mem;
  973. int ret = 0, i;
  974. if (!s->manual_dirty_log_protect) {
  975. /* No need to do explicit clear */
  976. return ret;
  977. }
  978. start = section->offset_within_address_space;
  979. size = int128_get64(section->size);
  980. if (!size) {
  981. /* Nothing more we can do... */
  982. return ret;
  983. }
  984. kvm_slots_lock();
  985. for (i = 0; i < kml->nr_slots_allocated; i++) {
  986. mem = &kml->slots[i];
  987. /* Discard slots that are empty or do not overlap the section */
  988. if (!mem->memory_size ||
  989. mem->start_addr > start + size - 1 ||
  990. start > mem->start_addr + mem->memory_size - 1) {
  991. continue;
  992. }
  993. if (start >= mem->start_addr) {
  994. /* The slot starts before section or is aligned to it. */
  995. offset = start - mem->start_addr;
  996. count = MIN(mem->memory_size - offset, size);
  997. } else {
  998. /* The slot starts after section. */
  999. offset = 0;
  1000. count = MIN(mem->memory_size, size - (mem->start_addr - start));
  1001. }
  1002. ret = kvm_log_clear_one_slot(mem, kml->as_id, offset, count);
  1003. if (ret < 0) {
  1004. break;
  1005. }
  1006. }
  1007. kvm_slots_unlock();
  1008. return ret;
  1009. }
  1010. static void kvm_coalesce_mmio_region(MemoryListener *listener,
  1011. MemoryRegionSection *secion,
  1012. hwaddr start, hwaddr size)
  1013. {
  1014. KVMState *s = kvm_state;
  1015. if (s->coalesced_mmio) {
  1016. struct kvm_coalesced_mmio_zone zone;
  1017. zone.addr = start;
  1018. zone.size = size;
  1019. zone.pad = 0;
  1020. (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
  1021. }
  1022. }
  1023. static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
  1024. MemoryRegionSection *secion,
  1025. hwaddr start, hwaddr size)
  1026. {
  1027. KVMState *s = kvm_state;
  1028. if (s->coalesced_mmio) {
  1029. struct kvm_coalesced_mmio_zone zone;
  1030. zone.addr = start;
  1031. zone.size = size;
  1032. zone.pad = 0;
  1033. (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
  1034. }
  1035. }
  1036. static void kvm_coalesce_pio_add(MemoryListener *listener,
  1037. MemoryRegionSection *section,
  1038. hwaddr start, hwaddr size)
  1039. {
  1040. KVMState *s = kvm_state;
  1041. if (s->coalesced_pio) {
  1042. struct kvm_coalesced_mmio_zone zone;
  1043. zone.addr = start;
  1044. zone.size = size;
  1045. zone.pio = 1;
  1046. (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
  1047. }
  1048. }
  1049. static void kvm_coalesce_pio_del(MemoryListener *listener,
  1050. MemoryRegionSection *section,
  1051. hwaddr start, hwaddr size)
  1052. {
  1053. KVMState *s = kvm_state;
  1054. if (s->coalesced_pio) {
  1055. struct kvm_coalesced_mmio_zone zone;
  1056. zone.addr = start;
  1057. zone.size = size;
  1058. zone.pio = 1;
  1059. (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
  1060. }
  1061. }
  1062. int kvm_check_extension(KVMState *s, unsigned int extension)
  1063. {
  1064. int ret;
  1065. ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
  1066. if (ret < 0) {
  1067. ret = 0;
  1068. }
  1069. return ret;
  1070. }
  1071. int kvm_vm_check_extension(KVMState *s, unsigned int extension)
  1072. {
  1073. int ret;
  1074. ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
  1075. if (ret < 0) {
  1076. /* VM wide version not implemented, use global one instead */
  1077. ret = kvm_check_extension(s, extension);
  1078. }
  1079. return ret;
  1080. }
  1081. /*
  1082. * We track the poisoned pages to be able to:
  1083. * - replace them on VM reset
  1084. * - block a migration for a VM with a poisoned page
  1085. */
  1086. typedef struct HWPoisonPage {
  1087. ram_addr_t ram_addr;
  1088. QLIST_ENTRY(HWPoisonPage) list;
  1089. } HWPoisonPage;
  1090. static QLIST_HEAD(, HWPoisonPage) hwpoison_page_list =
  1091. QLIST_HEAD_INITIALIZER(hwpoison_page_list);
  1092. static void kvm_unpoison_all(void *param)
  1093. {
  1094. HWPoisonPage *page, *next_page;
  1095. QLIST_FOREACH_SAFE(page, &hwpoison_page_list, list, next_page) {
  1096. QLIST_REMOVE(page, list);
  1097. qemu_ram_remap(page->ram_addr);
  1098. g_free(page);
  1099. }
  1100. }
  1101. void kvm_hwpoison_page_add(ram_addr_t ram_addr)
  1102. {
  1103. HWPoisonPage *page;
  1104. QLIST_FOREACH(page, &hwpoison_page_list, list) {
  1105. if (page->ram_addr == ram_addr) {
  1106. return;
  1107. }
  1108. }
  1109. page = g_new(HWPoisonPage, 1);
  1110. page->ram_addr = ram_addr;
  1111. QLIST_INSERT_HEAD(&hwpoison_page_list, page, list);
  1112. }
  1113. bool kvm_hwpoisoned_mem(void)
  1114. {
  1115. return !QLIST_EMPTY(&hwpoison_page_list);
  1116. }
  1117. static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
  1118. {
  1119. #if HOST_BIG_ENDIAN != TARGET_BIG_ENDIAN
  1120. /* The kernel expects ioeventfd values in HOST_BIG_ENDIAN
  1121. * endianness, but the memory core hands them in target endianness.
  1122. * For example, PPC is always treated as big-endian even if running
  1123. * on KVM and on PPC64LE. Correct here.
  1124. */
  1125. switch (size) {
  1126. case 2:
  1127. val = bswap16(val);
  1128. break;
  1129. case 4:
  1130. val = bswap32(val);
  1131. break;
  1132. }
  1133. #endif
  1134. return val;
  1135. }
  1136. static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
  1137. bool assign, uint32_t size, bool datamatch)
  1138. {
  1139. int ret;
  1140. struct kvm_ioeventfd iofd = {
  1141. .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
  1142. .addr = addr,
  1143. .len = size,
  1144. .flags = 0,
  1145. .fd = fd,
  1146. };
  1147. trace_kvm_set_ioeventfd_mmio(fd, (uint64_t)addr, val, assign, size,
  1148. datamatch);
  1149. if (!kvm_enabled()) {
  1150. return -ENOSYS;
  1151. }
  1152. if (datamatch) {
  1153. iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
  1154. }
  1155. if (!assign) {
  1156. iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
  1157. }
  1158. ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
  1159. if (ret < 0) {
  1160. return -errno;
  1161. }
  1162. return 0;
  1163. }
  1164. static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
  1165. bool assign, uint32_t size, bool datamatch)
  1166. {
  1167. struct kvm_ioeventfd kick = {
  1168. .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
  1169. .addr = addr,
  1170. .flags = KVM_IOEVENTFD_FLAG_PIO,
  1171. .len = size,
  1172. .fd = fd,
  1173. };
  1174. int r;
  1175. trace_kvm_set_ioeventfd_pio(fd, addr, val, assign, size, datamatch);
  1176. if (!kvm_enabled()) {
  1177. return -ENOSYS;
  1178. }
  1179. if (datamatch) {
  1180. kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
  1181. }
  1182. if (!assign) {
  1183. kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
  1184. }
  1185. r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
  1186. if (r < 0) {
  1187. return r;
  1188. }
  1189. return 0;
  1190. }
  1191. static const KVMCapabilityInfo *
  1192. kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
  1193. {
  1194. while (list->name) {
  1195. if (!kvm_check_extension(s, list->value)) {
  1196. return list;
  1197. }
  1198. list++;
  1199. }
  1200. return NULL;
  1201. }
  1202. void kvm_set_max_memslot_size(hwaddr max_slot_size)
  1203. {
  1204. g_assert(
  1205. ROUND_UP(max_slot_size, qemu_real_host_page_size()) == max_slot_size
  1206. );
  1207. kvm_max_slot_size = max_slot_size;
  1208. }
  1209. static int kvm_set_memory_attributes(hwaddr start, uint64_t size, uint64_t attr)
  1210. {
  1211. struct kvm_memory_attributes attrs;
  1212. int r;
  1213. assert((attr & kvm_supported_memory_attributes) == attr);
  1214. attrs.attributes = attr;
  1215. attrs.address = start;
  1216. attrs.size = size;
  1217. attrs.flags = 0;
  1218. r = kvm_vm_ioctl(kvm_state, KVM_SET_MEMORY_ATTRIBUTES, &attrs);
  1219. if (r) {
  1220. error_report("failed to set memory (0x%" HWADDR_PRIx "+0x%" PRIx64 ") "
  1221. "with attr 0x%" PRIx64 " error '%s'",
  1222. start, size, attr, strerror(errno));
  1223. }
  1224. return r;
  1225. }
  1226. int kvm_set_memory_attributes_private(hwaddr start, uint64_t size)
  1227. {
  1228. return kvm_set_memory_attributes(start, size, KVM_MEMORY_ATTRIBUTE_PRIVATE);
  1229. }
  1230. int kvm_set_memory_attributes_shared(hwaddr start, uint64_t size)
  1231. {
  1232. return kvm_set_memory_attributes(start, size, 0);
  1233. }
  1234. /* Called with KVMMemoryListener.slots_lock held */
  1235. static void kvm_set_phys_mem(KVMMemoryListener *kml,
  1236. MemoryRegionSection *section, bool add)
  1237. {
  1238. KVMSlot *mem;
  1239. int err;
  1240. MemoryRegion *mr = section->mr;
  1241. bool writable = !mr->readonly && !mr->rom_device;
  1242. hwaddr start_addr, size, slot_size, mr_offset;
  1243. ram_addr_t ram_start_offset;
  1244. void *ram;
  1245. if (!memory_region_is_ram(mr)) {
  1246. if (writable || !kvm_readonly_mem_allowed) {
  1247. return;
  1248. } else if (!mr->romd_mode) {
  1249. /* If the memory device is not in romd_mode, then we actually want
  1250. * to remove the kvm memory slot so all accesses will trap. */
  1251. add = false;
  1252. }
  1253. }
  1254. size = kvm_align_section(section, &start_addr);
  1255. if (!size) {
  1256. return;
  1257. }
  1258. /* The offset of the kvmslot within the memory region */
  1259. mr_offset = section->offset_within_region + start_addr -
  1260. section->offset_within_address_space;
  1261. /* use aligned delta to align the ram address and offset */
  1262. ram = memory_region_get_ram_ptr(mr) + mr_offset;
  1263. ram_start_offset = memory_region_get_ram_addr(mr) + mr_offset;
  1264. if (!add) {
  1265. do {
  1266. slot_size = MIN(kvm_max_slot_size, size);
  1267. mem = kvm_lookup_matching_slot(kml, start_addr, slot_size);
  1268. if (!mem) {
  1269. return;
  1270. }
  1271. if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  1272. /*
  1273. * NOTE: We should be aware of the fact that here we're only
  1274. * doing a best effort to sync dirty bits. No matter whether
  1275. * we're using dirty log or dirty ring, we ignored two facts:
  1276. *
  1277. * (1) dirty bits can reside in hardware buffers (PML)
  1278. *
  1279. * (2) after we collected dirty bits here, pages can be dirtied
  1280. * again before we do the final KVM_SET_USER_MEMORY_REGION to
  1281. * remove the slot.
  1282. *
  1283. * Not easy. Let's cross the fingers until it's fixed.
  1284. */
  1285. if (kvm_state->kvm_dirty_ring_size) {
  1286. kvm_dirty_ring_reap_locked(kvm_state, NULL);
  1287. if (kvm_state->kvm_dirty_ring_with_bitmap) {
  1288. kvm_slot_sync_dirty_pages(mem);
  1289. kvm_slot_get_dirty_log(kvm_state, mem);
  1290. }
  1291. } else {
  1292. kvm_slot_get_dirty_log(kvm_state, mem);
  1293. }
  1294. kvm_slot_sync_dirty_pages(mem);
  1295. }
  1296. /* unregister the slot */
  1297. g_free(mem->dirty_bmap);
  1298. mem->dirty_bmap = NULL;
  1299. mem->memory_size = 0;
  1300. mem->flags = 0;
  1301. err = kvm_set_user_memory_region(kml, mem, false);
  1302. if (err) {
  1303. fprintf(stderr, "%s: error unregistering slot: %s\n",
  1304. __func__, strerror(-err));
  1305. abort();
  1306. }
  1307. start_addr += slot_size;
  1308. size -= slot_size;
  1309. kml->nr_slots_used--;
  1310. } while (size);
  1311. return;
  1312. }
  1313. /* register the new slot */
  1314. do {
  1315. slot_size = MIN(kvm_max_slot_size, size);
  1316. mem = kvm_alloc_slot(kml);
  1317. mem->as_id = kml->as_id;
  1318. mem->memory_size = slot_size;
  1319. mem->start_addr = start_addr;
  1320. mem->ram_start_offset = ram_start_offset;
  1321. mem->ram = ram;
  1322. mem->flags = kvm_mem_flags(mr);
  1323. mem->guest_memfd = mr->ram_block->guest_memfd;
  1324. mem->guest_memfd_offset = (uint8_t*)ram - mr->ram_block->host;
  1325. kvm_slot_init_dirty_bitmap(mem);
  1326. err = kvm_set_user_memory_region(kml, mem, true);
  1327. if (err) {
  1328. fprintf(stderr, "%s: error registering slot: %s\n", __func__,
  1329. strerror(-err));
  1330. abort();
  1331. }
  1332. if (memory_region_has_guest_memfd(mr)) {
  1333. err = kvm_set_memory_attributes_private(start_addr, slot_size);
  1334. if (err) {
  1335. error_report("%s: failed to set memory attribute private: %s",
  1336. __func__, strerror(-err));
  1337. exit(1);
  1338. }
  1339. }
  1340. start_addr += slot_size;
  1341. ram_start_offset += slot_size;
  1342. ram += slot_size;
  1343. size -= slot_size;
  1344. kml->nr_slots_used++;
  1345. } while (size);
  1346. }
  1347. static void *kvm_dirty_ring_reaper_thread(void *data)
  1348. {
  1349. KVMState *s = data;
  1350. struct KVMDirtyRingReaper *r = &s->reaper;
  1351. rcu_register_thread();
  1352. trace_kvm_dirty_ring_reaper("init");
  1353. while (true) {
  1354. r->reaper_state = KVM_DIRTY_RING_REAPER_WAIT;
  1355. trace_kvm_dirty_ring_reaper("wait");
  1356. /*
  1357. * TODO: provide a smarter timeout rather than a constant?
  1358. */
  1359. sleep(1);
  1360. /* keep sleeping so that dirtylimit not be interfered by reaper */
  1361. if (dirtylimit_in_service()) {
  1362. continue;
  1363. }
  1364. trace_kvm_dirty_ring_reaper("wakeup");
  1365. r->reaper_state = KVM_DIRTY_RING_REAPER_REAPING;
  1366. bql_lock();
  1367. kvm_dirty_ring_reap(s, NULL);
  1368. bql_unlock();
  1369. r->reaper_iteration++;
  1370. }
  1371. g_assert_not_reached();
  1372. }
  1373. static void kvm_dirty_ring_reaper_init(KVMState *s)
  1374. {
  1375. struct KVMDirtyRingReaper *r = &s->reaper;
  1376. qemu_thread_create(&r->reaper_thr, "kvm-reaper",
  1377. kvm_dirty_ring_reaper_thread,
  1378. s, QEMU_THREAD_JOINABLE);
  1379. }
  1380. static int kvm_dirty_ring_init(KVMState *s)
  1381. {
  1382. uint32_t ring_size = s->kvm_dirty_ring_size;
  1383. uint64_t ring_bytes = ring_size * sizeof(struct kvm_dirty_gfn);
  1384. unsigned int capability = KVM_CAP_DIRTY_LOG_RING;
  1385. int ret;
  1386. s->kvm_dirty_ring_size = 0;
  1387. s->kvm_dirty_ring_bytes = 0;
  1388. /* Bail if the dirty ring size isn't specified */
  1389. if (!ring_size) {
  1390. return 0;
  1391. }
  1392. /*
  1393. * Read the max supported pages. Fall back to dirty logging mode
  1394. * if the dirty ring isn't supported.
  1395. */
  1396. ret = kvm_vm_check_extension(s, capability);
  1397. if (ret <= 0) {
  1398. capability = KVM_CAP_DIRTY_LOG_RING_ACQ_REL;
  1399. ret = kvm_vm_check_extension(s, capability);
  1400. }
  1401. if (ret <= 0) {
  1402. warn_report("KVM dirty ring not available, using bitmap method");
  1403. return 0;
  1404. }
  1405. if (ring_bytes > ret) {
  1406. error_report("KVM dirty ring size %" PRIu32 " too big "
  1407. "(maximum is %ld). Please use a smaller value.",
  1408. ring_size, (long)ret / sizeof(struct kvm_dirty_gfn));
  1409. return -EINVAL;
  1410. }
  1411. ret = kvm_vm_enable_cap(s, capability, 0, ring_bytes);
  1412. if (ret) {
  1413. error_report("Enabling of KVM dirty ring failed: %s. "
  1414. "Suggested minimum value is 1024.", strerror(-ret));
  1415. return -EIO;
  1416. }
  1417. /* Enable the backup bitmap if it is supported */
  1418. ret = kvm_vm_check_extension(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP);
  1419. if (ret > 0) {
  1420. ret = kvm_vm_enable_cap(s, KVM_CAP_DIRTY_LOG_RING_WITH_BITMAP, 0);
  1421. if (ret) {
  1422. error_report("Enabling of KVM dirty ring's backup bitmap failed: "
  1423. "%s. ", strerror(-ret));
  1424. return -EIO;
  1425. }
  1426. s->kvm_dirty_ring_with_bitmap = true;
  1427. }
  1428. s->kvm_dirty_ring_size = ring_size;
  1429. s->kvm_dirty_ring_bytes = ring_bytes;
  1430. return 0;
  1431. }
  1432. static void kvm_region_add(MemoryListener *listener,
  1433. MemoryRegionSection *section)
  1434. {
  1435. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  1436. KVMMemoryUpdate *update;
  1437. update = g_new0(KVMMemoryUpdate, 1);
  1438. update->section = *section;
  1439. QSIMPLEQ_INSERT_TAIL(&kml->transaction_add, update, next);
  1440. }
  1441. static void kvm_region_del(MemoryListener *listener,
  1442. MemoryRegionSection *section)
  1443. {
  1444. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  1445. KVMMemoryUpdate *update;
  1446. update = g_new0(KVMMemoryUpdate, 1);
  1447. update->section = *section;
  1448. QSIMPLEQ_INSERT_TAIL(&kml->transaction_del, update, next);
  1449. }
  1450. static void kvm_region_commit(MemoryListener *listener)
  1451. {
  1452. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener,
  1453. listener);
  1454. KVMMemoryUpdate *u1, *u2;
  1455. bool need_inhibit = false;
  1456. if (QSIMPLEQ_EMPTY(&kml->transaction_add) &&
  1457. QSIMPLEQ_EMPTY(&kml->transaction_del)) {
  1458. return;
  1459. }
  1460. /*
  1461. * We have to be careful when regions to add overlap with ranges to remove.
  1462. * We have to simulate atomic KVM memslot updates by making sure no ioctl()
  1463. * is currently active.
  1464. *
  1465. * The lists are order by addresses, so it's easy to find overlaps.
  1466. */
  1467. u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
  1468. u2 = QSIMPLEQ_FIRST(&kml->transaction_add);
  1469. while (u1 && u2) {
  1470. Range r1, r2;
  1471. range_init_nofail(&r1, u1->section.offset_within_address_space,
  1472. int128_get64(u1->section.size));
  1473. range_init_nofail(&r2, u2->section.offset_within_address_space,
  1474. int128_get64(u2->section.size));
  1475. if (range_overlaps_range(&r1, &r2)) {
  1476. need_inhibit = true;
  1477. break;
  1478. }
  1479. if (range_lob(&r1) < range_lob(&r2)) {
  1480. u1 = QSIMPLEQ_NEXT(u1, next);
  1481. } else {
  1482. u2 = QSIMPLEQ_NEXT(u2, next);
  1483. }
  1484. }
  1485. kvm_slots_lock();
  1486. if (need_inhibit) {
  1487. accel_ioctl_inhibit_begin();
  1488. }
  1489. /* Remove all memslots before adding the new ones. */
  1490. while (!QSIMPLEQ_EMPTY(&kml->transaction_del)) {
  1491. u1 = QSIMPLEQ_FIRST(&kml->transaction_del);
  1492. QSIMPLEQ_REMOVE_HEAD(&kml->transaction_del, next);
  1493. kvm_set_phys_mem(kml, &u1->section, false);
  1494. memory_region_unref(u1->section.mr);
  1495. g_free(u1);
  1496. }
  1497. while (!QSIMPLEQ_EMPTY(&kml->transaction_add)) {
  1498. u1 = QSIMPLEQ_FIRST(&kml->transaction_add);
  1499. QSIMPLEQ_REMOVE_HEAD(&kml->transaction_add, next);
  1500. memory_region_ref(u1->section.mr);
  1501. kvm_set_phys_mem(kml, &u1->section, true);
  1502. g_free(u1);
  1503. }
  1504. if (need_inhibit) {
  1505. accel_ioctl_inhibit_end();
  1506. }
  1507. kvm_slots_unlock();
  1508. }
  1509. static void kvm_log_sync(MemoryListener *listener,
  1510. MemoryRegionSection *section)
  1511. {
  1512. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  1513. kvm_slots_lock();
  1514. kvm_physical_sync_dirty_bitmap(kml, section);
  1515. kvm_slots_unlock();
  1516. }
  1517. static void kvm_log_sync_global(MemoryListener *l, bool last_stage)
  1518. {
  1519. KVMMemoryListener *kml = container_of(l, KVMMemoryListener, listener);
  1520. KVMState *s = kvm_state;
  1521. KVMSlot *mem;
  1522. int i;
  1523. /* Flush all kernel dirty addresses into KVMSlot dirty bitmap */
  1524. kvm_dirty_ring_flush();
  1525. kvm_slots_lock();
  1526. for (i = 0; i < kml->nr_slots_allocated; i++) {
  1527. mem = &kml->slots[i];
  1528. if (mem->memory_size && mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  1529. kvm_slot_sync_dirty_pages(mem);
  1530. if (s->kvm_dirty_ring_with_bitmap && last_stage &&
  1531. kvm_slot_get_dirty_log(s, mem)) {
  1532. kvm_slot_sync_dirty_pages(mem);
  1533. }
  1534. /*
  1535. * This is not needed by KVM_GET_DIRTY_LOG because the
  1536. * ioctl will unconditionally overwrite the whole region.
  1537. * However kvm dirty ring has no such side effect.
  1538. */
  1539. kvm_slot_reset_dirty_pages(mem);
  1540. }
  1541. }
  1542. kvm_slots_unlock();
  1543. }
  1544. static void kvm_log_clear(MemoryListener *listener,
  1545. MemoryRegionSection *section)
  1546. {
  1547. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  1548. int r;
  1549. r = kvm_physical_log_clear(kml, section);
  1550. if (r < 0) {
  1551. error_report_once("%s: kvm log clear failed: mr=%s "
  1552. "offset=%"HWADDR_PRIx" size=%"PRIx64, __func__,
  1553. section->mr->name, section->offset_within_region,
  1554. int128_get64(section->size));
  1555. abort();
  1556. }
  1557. }
  1558. static void kvm_mem_ioeventfd_add(MemoryListener *listener,
  1559. MemoryRegionSection *section,
  1560. bool match_data, uint64_t data,
  1561. EventNotifier *e)
  1562. {
  1563. int fd = event_notifier_get_fd(e);
  1564. int r;
  1565. r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
  1566. data, true, int128_get64(section->size),
  1567. match_data);
  1568. if (r < 0) {
  1569. fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
  1570. __func__, strerror(-r), -r);
  1571. abort();
  1572. }
  1573. }
  1574. static void kvm_mem_ioeventfd_del(MemoryListener *listener,
  1575. MemoryRegionSection *section,
  1576. bool match_data, uint64_t data,
  1577. EventNotifier *e)
  1578. {
  1579. int fd = event_notifier_get_fd(e);
  1580. int r;
  1581. r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
  1582. data, false, int128_get64(section->size),
  1583. match_data);
  1584. if (r < 0) {
  1585. fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
  1586. __func__, strerror(-r), -r);
  1587. abort();
  1588. }
  1589. }
  1590. static void kvm_io_ioeventfd_add(MemoryListener *listener,
  1591. MemoryRegionSection *section,
  1592. bool match_data, uint64_t data,
  1593. EventNotifier *e)
  1594. {
  1595. int fd = event_notifier_get_fd(e);
  1596. int r;
  1597. r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
  1598. data, true, int128_get64(section->size),
  1599. match_data);
  1600. if (r < 0) {
  1601. fprintf(stderr, "%s: error adding ioeventfd: %s (%d)\n",
  1602. __func__, strerror(-r), -r);
  1603. abort();
  1604. }
  1605. }
  1606. static void kvm_io_ioeventfd_del(MemoryListener *listener,
  1607. MemoryRegionSection *section,
  1608. bool match_data, uint64_t data,
  1609. EventNotifier *e)
  1610. {
  1611. int fd = event_notifier_get_fd(e);
  1612. int r;
  1613. r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
  1614. data, false, int128_get64(section->size),
  1615. match_data);
  1616. if (r < 0) {
  1617. fprintf(stderr, "%s: error deleting ioeventfd: %s (%d)\n",
  1618. __func__, strerror(-r), -r);
  1619. abort();
  1620. }
  1621. }
  1622. void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
  1623. AddressSpace *as, int as_id, const char *name)
  1624. {
  1625. int i;
  1626. kml->as_id = as_id;
  1627. kvm_slots_grow(kml, KVM_MEMSLOTS_NR_ALLOC_DEFAULT);
  1628. QSIMPLEQ_INIT(&kml->transaction_add);
  1629. QSIMPLEQ_INIT(&kml->transaction_del);
  1630. kml->listener.region_add = kvm_region_add;
  1631. kml->listener.region_del = kvm_region_del;
  1632. kml->listener.commit = kvm_region_commit;
  1633. kml->listener.log_start = kvm_log_start;
  1634. kml->listener.log_stop = kvm_log_stop;
  1635. kml->listener.priority = MEMORY_LISTENER_PRIORITY_ACCEL;
  1636. kml->listener.name = name;
  1637. if (s->kvm_dirty_ring_size) {
  1638. kml->listener.log_sync_global = kvm_log_sync_global;
  1639. } else {
  1640. kml->listener.log_sync = kvm_log_sync;
  1641. kml->listener.log_clear = kvm_log_clear;
  1642. }
  1643. memory_listener_register(&kml->listener, as);
  1644. for (i = 0; i < s->nr_as; ++i) {
  1645. if (!s->as[i].as) {
  1646. s->as[i].as = as;
  1647. s->as[i].ml = kml;
  1648. break;
  1649. }
  1650. }
  1651. }
  1652. static MemoryListener kvm_io_listener = {
  1653. .name = "kvm-io",
  1654. .coalesced_io_add = kvm_coalesce_pio_add,
  1655. .coalesced_io_del = kvm_coalesce_pio_del,
  1656. .eventfd_add = kvm_io_ioeventfd_add,
  1657. .eventfd_del = kvm_io_ioeventfd_del,
  1658. .priority = MEMORY_LISTENER_PRIORITY_DEV_BACKEND,
  1659. };
  1660. int kvm_set_irq(KVMState *s, int irq, int level)
  1661. {
  1662. struct kvm_irq_level event;
  1663. int ret;
  1664. assert(kvm_async_interrupts_enabled());
  1665. event.level = level;
  1666. event.irq = irq;
  1667. ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
  1668. if (ret < 0) {
  1669. perror("kvm_set_irq");
  1670. abort();
  1671. }
  1672. return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
  1673. }
  1674. #ifdef KVM_CAP_IRQ_ROUTING
  1675. typedef struct KVMMSIRoute {
  1676. struct kvm_irq_routing_entry kroute;
  1677. QTAILQ_ENTRY(KVMMSIRoute) entry;
  1678. } KVMMSIRoute;
  1679. static void set_gsi(KVMState *s, unsigned int gsi)
  1680. {
  1681. set_bit(gsi, s->used_gsi_bitmap);
  1682. }
  1683. static void clear_gsi(KVMState *s, unsigned int gsi)
  1684. {
  1685. clear_bit(gsi, s->used_gsi_bitmap);
  1686. }
  1687. void kvm_init_irq_routing(KVMState *s)
  1688. {
  1689. int gsi_count;
  1690. gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
  1691. if (gsi_count > 0) {
  1692. /* Round up so we can search ints using ffs */
  1693. s->used_gsi_bitmap = bitmap_new(gsi_count);
  1694. s->gsi_count = gsi_count;
  1695. }
  1696. s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
  1697. s->nr_allocated_irq_routes = 0;
  1698. kvm_arch_init_irq_routing(s);
  1699. }
  1700. void kvm_irqchip_commit_routes(KVMState *s)
  1701. {
  1702. int ret;
  1703. if (kvm_gsi_direct_mapping()) {
  1704. return;
  1705. }
  1706. if (!kvm_gsi_routing_enabled()) {
  1707. return;
  1708. }
  1709. s->irq_routes->flags = 0;
  1710. trace_kvm_irqchip_commit_routes();
  1711. ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
  1712. assert(ret == 0);
  1713. }
  1714. void kvm_add_routing_entry(KVMState *s,
  1715. struct kvm_irq_routing_entry *entry)
  1716. {
  1717. struct kvm_irq_routing_entry *new;
  1718. int n, size;
  1719. if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
  1720. n = s->nr_allocated_irq_routes * 2;
  1721. if (n < 64) {
  1722. n = 64;
  1723. }
  1724. size = sizeof(struct kvm_irq_routing);
  1725. size += n * sizeof(*new);
  1726. s->irq_routes = g_realloc(s->irq_routes, size);
  1727. s->nr_allocated_irq_routes = n;
  1728. }
  1729. n = s->irq_routes->nr++;
  1730. new = &s->irq_routes->entries[n];
  1731. *new = *entry;
  1732. set_gsi(s, entry->gsi);
  1733. }
  1734. static int kvm_update_routing_entry(KVMState *s,
  1735. struct kvm_irq_routing_entry *new_entry)
  1736. {
  1737. struct kvm_irq_routing_entry *entry;
  1738. int n;
  1739. for (n = 0; n < s->irq_routes->nr; n++) {
  1740. entry = &s->irq_routes->entries[n];
  1741. if (entry->gsi != new_entry->gsi) {
  1742. continue;
  1743. }
  1744. if(!memcmp(entry, new_entry, sizeof *entry)) {
  1745. return 0;
  1746. }
  1747. *entry = *new_entry;
  1748. return 0;
  1749. }
  1750. return -ESRCH;
  1751. }
  1752. void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
  1753. {
  1754. struct kvm_irq_routing_entry e = {};
  1755. assert(pin < s->gsi_count);
  1756. e.gsi = irq;
  1757. e.type = KVM_IRQ_ROUTING_IRQCHIP;
  1758. e.flags = 0;
  1759. e.u.irqchip.irqchip = irqchip;
  1760. e.u.irqchip.pin = pin;
  1761. kvm_add_routing_entry(s, &e);
  1762. }
  1763. void kvm_irqchip_release_virq(KVMState *s, int virq)
  1764. {
  1765. struct kvm_irq_routing_entry *e;
  1766. int i;
  1767. if (kvm_gsi_direct_mapping()) {
  1768. return;
  1769. }
  1770. for (i = 0; i < s->irq_routes->nr; i++) {
  1771. e = &s->irq_routes->entries[i];
  1772. if (e->gsi == virq) {
  1773. s->irq_routes->nr--;
  1774. *e = s->irq_routes->entries[s->irq_routes->nr];
  1775. }
  1776. }
  1777. clear_gsi(s, virq);
  1778. kvm_arch_release_virq_post(virq);
  1779. trace_kvm_irqchip_release_virq(virq);
  1780. }
  1781. void kvm_irqchip_add_change_notifier(Notifier *n)
  1782. {
  1783. notifier_list_add(&kvm_irqchip_change_notifiers, n);
  1784. }
  1785. void kvm_irqchip_remove_change_notifier(Notifier *n)
  1786. {
  1787. notifier_remove(n);
  1788. }
  1789. void kvm_irqchip_change_notify(void)
  1790. {
  1791. notifier_list_notify(&kvm_irqchip_change_notifiers, NULL);
  1792. }
  1793. int kvm_irqchip_get_virq(KVMState *s)
  1794. {
  1795. int next_virq;
  1796. /* Return the lowest unused GSI in the bitmap */
  1797. next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
  1798. if (next_virq >= s->gsi_count) {
  1799. return -ENOSPC;
  1800. } else {
  1801. return next_virq;
  1802. }
  1803. }
  1804. int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
  1805. {
  1806. struct kvm_msi msi;
  1807. msi.address_lo = (uint32_t)msg.address;
  1808. msi.address_hi = msg.address >> 32;
  1809. msi.data = le32_to_cpu(msg.data);
  1810. msi.flags = 0;
  1811. memset(msi.pad, 0, sizeof(msi.pad));
  1812. return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
  1813. }
  1814. int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
  1815. {
  1816. struct kvm_irq_routing_entry kroute = {};
  1817. int virq;
  1818. KVMState *s = c->s;
  1819. MSIMessage msg = {0, 0};
  1820. if (pci_available && dev) {
  1821. msg = pci_get_msi_message(dev, vector);
  1822. }
  1823. if (kvm_gsi_direct_mapping()) {
  1824. return kvm_arch_msi_data_to_gsi(msg.data);
  1825. }
  1826. if (!kvm_gsi_routing_enabled()) {
  1827. return -ENOSYS;
  1828. }
  1829. virq = kvm_irqchip_get_virq(s);
  1830. if (virq < 0) {
  1831. return virq;
  1832. }
  1833. kroute.gsi = virq;
  1834. kroute.type = KVM_IRQ_ROUTING_MSI;
  1835. kroute.flags = 0;
  1836. kroute.u.msi.address_lo = (uint32_t)msg.address;
  1837. kroute.u.msi.address_hi = msg.address >> 32;
  1838. kroute.u.msi.data = le32_to_cpu(msg.data);
  1839. if (pci_available && kvm_msi_devid_required()) {
  1840. kroute.flags = KVM_MSI_VALID_DEVID;
  1841. kroute.u.msi.devid = pci_requester_id(dev);
  1842. }
  1843. if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
  1844. kvm_irqchip_release_virq(s, virq);
  1845. return -EINVAL;
  1846. }
  1847. if (s->irq_routes->nr < s->gsi_count) {
  1848. trace_kvm_irqchip_add_msi_route(dev ? dev->name : (char *)"N/A",
  1849. vector, virq);
  1850. kvm_add_routing_entry(s, &kroute);
  1851. kvm_arch_add_msi_route_post(&kroute, vector, dev);
  1852. c->changes++;
  1853. } else {
  1854. kvm_irqchip_release_virq(s, virq);
  1855. return -ENOSPC;
  1856. }
  1857. return virq;
  1858. }
  1859. int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
  1860. PCIDevice *dev)
  1861. {
  1862. struct kvm_irq_routing_entry kroute = {};
  1863. if (kvm_gsi_direct_mapping()) {
  1864. return 0;
  1865. }
  1866. if (!kvm_irqchip_in_kernel()) {
  1867. return -ENOSYS;
  1868. }
  1869. kroute.gsi = virq;
  1870. kroute.type = KVM_IRQ_ROUTING_MSI;
  1871. kroute.flags = 0;
  1872. kroute.u.msi.address_lo = (uint32_t)msg.address;
  1873. kroute.u.msi.address_hi = msg.address >> 32;
  1874. kroute.u.msi.data = le32_to_cpu(msg.data);
  1875. if (pci_available && kvm_msi_devid_required()) {
  1876. kroute.flags = KVM_MSI_VALID_DEVID;
  1877. kroute.u.msi.devid = pci_requester_id(dev);
  1878. }
  1879. if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
  1880. return -EINVAL;
  1881. }
  1882. trace_kvm_irqchip_update_msi_route(virq);
  1883. return kvm_update_routing_entry(s, &kroute);
  1884. }
  1885. static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
  1886. EventNotifier *resample, int virq,
  1887. bool assign)
  1888. {
  1889. int fd = event_notifier_get_fd(event);
  1890. int rfd = resample ? event_notifier_get_fd(resample) : -1;
  1891. struct kvm_irqfd irqfd = {
  1892. .fd = fd,
  1893. .gsi = virq,
  1894. .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
  1895. };
  1896. if (rfd != -1) {
  1897. assert(assign);
  1898. if (kvm_irqchip_is_split()) {
  1899. /*
  1900. * When the slow irqchip (e.g. IOAPIC) is in the
  1901. * userspace, KVM kernel resamplefd will not work because
  1902. * the EOI of the interrupt will be delivered to userspace
  1903. * instead, so the KVM kernel resamplefd kick will be
  1904. * skipped. The userspace here mimics what the kernel
  1905. * provides with resamplefd, remember the resamplefd and
  1906. * kick it when we receive EOI of this IRQ.
  1907. *
  1908. * This is hackery because IOAPIC is mostly bypassed
  1909. * (except EOI broadcasts) when irqfd is used. However
  1910. * this can bring much performance back for split irqchip
  1911. * with INTx IRQs (for VFIO, this gives 93% perf of the
  1912. * full fast path, which is 46% perf boost comparing to
  1913. * the INTx slow path).
  1914. */
  1915. kvm_resample_fd_insert(virq, resample);
  1916. } else {
  1917. irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
  1918. irqfd.resamplefd = rfd;
  1919. }
  1920. } else if (!assign) {
  1921. if (kvm_irqchip_is_split()) {
  1922. kvm_resample_fd_remove(virq);
  1923. }
  1924. }
  1925. return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
  1926. }
  1927. #else /* !KVM_CAP_IRQ_ROUTING */
  1928. void kvm_init_irq_routing(KVMState *s)
  1929. {
  1930. }
  1931. void kvm_irqchip_release_virq(KVMState *s, int virq)
  1932. {
  1933. }
  1934. int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
  1935. {
  1936. abort();
  1937. }
  1938. int kvm_irqchip_add_msi_route(KVMRouteChange *c, int vector, PCIDevice *dev)
  1939. {
  1940. return -ENOSYS;
  1941. }
  1942. int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
  1943. {
  1944. return -ENOSYS;
  1945. }
  1946. int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
  1947. {
  1948. return -ENOSYS;
  1949. }
  1950. static int kvm_irqchip_assign_irqfd(KVMState *s, EventNotifier *event,
  1951. EventNotifier *resample, int virq,
  1952. bool assign)
  1953. {
  1954. abort();
  1955. }
  1956. int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
  1957. {
  1958. return -ENOSYS;
  1959. }
  1960. #endif /* !KVM_CAP_IRQ_ROUTING */
  1961. int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
  1962. EventNotifier *rn, int virq)
  1963. {
  1964. return kvm_irqchip_assign_irqfd(s, n, rn, virq, true);
  1965. }
  1966. int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
  1967. int virq)
  1968. {
  1969. return kvm_irqchip_assign_irqfd(s, n, NULL, virq, false);
  1970. }
  1971. int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
  1972. EventNotifier *rn, qemu_irq irq)
  1973. {
  1974. gpointer key, gsi;
  1975. gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
  1976. if (!found) {
  1977. return -ENXIO;
  1978. }
  1979. return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
  1980. }
  1981. int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
  1982. qemu_irq irq)
  1983. {
  1984. gpointer key, gsi;
  1985. gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
  1986. if (!found) {
  1987. return -ENXIO;
  1988. }
  1989. return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
  1990. }
  1991. void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
  1992. {
  1993. g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
  1994. }
  1995. static void kvm_irqchip_create(KVMState *s)
  1996. {
  1997. int ret;
  1998. assert(s->kernel_irqchip_split != ON_OFF_AUTO_AUTO);
  1999. if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
  2000. ;
  2001. } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
  2002. ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
  2003. if (ret < 0) {
  2004. fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
  2005. exit(1);
  2006. }
  2007. } else {
  2008. return;
  2009. }
  2010. if (kvm_check_extension(s, KVM_CAP_IRQFD) <= 0) {
  2011. fprintf(stderr, "kvm: irqfd not implemented\n");
  2012. exit(1);
  2013. }
  2014. /* First probe and see if there's a arch-specific hook to create the
  2015. * in-kernel irqchip for us */
  2016. ret = kvm_arch_irqchip_create(s);
  2017. if (ret == 0) {
  2018. if (s->kernel_irqchip_split == ON_OFF_AUTO_ON) {
  2019. error_report("Split IRQ chip mode not supported.");
  2020. exit(1);
  2021. } else {
  2022. ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
  2023. }
  2024. }
  2025. if (ret < 0) {
  2026. fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
  2027. exit(1);
  2028. }
  2029. kvm_kernel_irqchip = true;
  2030. /* If we have an in-kernel IRQ chip then we must have asynchronous
  2031. * interrupt delivery (though the reverse is not necessarily true)
  2032. */
  2033. kvm_async_interrupts_allowed = true;
  2034. kvm_halt_in_kernel_allowed = true;
  2035. kvm_init_irq_routing(s);
  2036. s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
  2037. }
  2038. /* Find number of supported CPUs using the recommended
  2039. * procedure from the kernel API documentation to cope with
  2040. * older kernels that may be missing capabilities.
  2041. */
  2042. static int kvm_recommended_vcpus(KVMState *s)
  2043. {
  2044. int ret = kvm_vm_check_extension(s, KVM_CAP_NR_VCPUS);
  2045. return (ret) ? ret : 4;
  2046. }
  2047. static int kvm_max_vcpus(KVMState *s)
  2048. {
  2049. int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
  2050. return (ret) ? ret : kvm_recommended_vcpus(s);
  2051. }
  2052. static int kvm_max_vcpu_id(KVMState *s)
  2053. {
  2054. int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
  2055. return (ret) ? ret : kvm_max_vcpus(s);
  2056. }
  2057. bool kvm_vcpu_id_is_valid(int vcpu_id)
  2058. {
  2059. KVMState *s = KVM_STATE(current_accel());
  2060. return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
  2061. }
  2062. bool kvm_dirty_ring_enabled(void)
  2063. {
  2064. return kvm_state && kvm_state->kvm_dirty_ring_size;
  2065. }
  2066. static void query_stats_cb(StatsResultList **result, StatsTarget target,
  2067. strList *names, strList *targets, Error **errp);
  2068. static void query_stats_schemas_cb(StatsSchemaList **result, Error **errp);
  2069. uint32_t kvm_dirty_ring_size(void)
  2070. {
  2071. return kvm_state->kvm_dirty_ring_size;
  2072. }
  2073. static int do_kvm_create_vm(MachineState *ms, int type)
  2074. {
  2075. KVMState *s;
  2076. int ret;
  2077. s = KVM_STATE(ms->accelerator);
  2078. do {
  2079. ret = kvm_ioctl(s, KVM_CREATE_VM, type);
  2080. } while (ret == -EINTR);
  2081. if (ret < 0) {
  2082. error_report("ioctl(KVM_CREATE_VM) failed: %s", strerror(-ret));
  2083. #ifdef TARGET_S390X
  2084. if (ret == -EINVAL) {
  2085. error_printf("Host kernel setup problem detected."
  2086. " Please verify:\n");
  2087. error_printf("- for kernels supporting the"
  2088. " switch_amode or user_mode parameters, whether");
  2089. error_printf(" user space is running in primary address space\n");
  2090. error_printf("- for kernels supporting the vm.allocate_pgste"
  2091. " sysctl, whether it is enabled\n");
  2092. }
  2093. #elif defined(TARGET_PPC)
  2094. if (ret == -EINVAL) {
  2095. error_printf("PPC KVM module is not loaded. Try modprobe kvm_%s.\n",
  2096. (type == 2) ? "pr" : "hv");
  2097. }
  2098. #endif
  2099. }
  2100. return ret;
  2101. }
  2102. static int find_kvm_machine_type(MachineState *ms)
  2103. {
  2104. MachineClass *mc = MACHINE_GET_CLASS(ms);
  2105. int type;
  2106. if (object_property_find(OBJECT(current_machine), "kvm-type")) {
  2107. g_autofree char *kvm_type;
  2108. kvm_type = object_property_get_str(OBJECT(current_machine),
  2109. "kvm-type",
  2110. &error_abort);
  2111. type = mc->kvm_type(ms, kvm_type);
  2112. } else if (mc->kvm_type) {
  2113. type = mc->kvm_type(ms, NULL);
  2114. } else {
  2115. type = kvm_arch_get_default_type(ms);
  2116. }
  2117. return type;
  2118. }
  2119. static int kvm_setup_dirty_ring(KVMState *s)
  2120. {
  2121. uint64_t dirty_log_manual_caps;
  2122. int ret;
  2123. /*
  2124. * Enable KVM dirty ring if supported, otherwise fall back to
  2125. * dirty logging mode
  2126. */
  2127. ret = kvm_dirty_ring_init(s);
  2128. if (ret < 0) {
  2129. return ret;
  2130. }
  2131. /*
  2132. * KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 is not needed when dirty ring is
  2133. * enabled. More importantly, KVM_DIRTY_LOG_INITIALLY_SET will assume no
  2134. * page is wr-protected initially, which is against how kvm dirty ring is
  2135. * usage - kvm dirty ring requires all pages are wr-protected at the very
  2136. * beginning. Enabling this feature for dirty ring causes data corruption.
  2137. *
  2138. * TODO: Without KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 and kvm clear dirty log,
  2139. * we may expect a higher stall time when starting the migration. In the
  2140. * future we can enable KVM_CLEAR_DIRTY_LOG to work with dirty ring too:
  2141. * instead of clearing dirty bit, it can be a way to explicitly wr-protect
  2142. * guest pages.
  2143. */
  2144. if (!s->kvm_dirty_ring_size) {
  2145. dirty_log_manual_caps =
  2146. kvm_check_extension(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2);
  2147. dirty_log_manual_caps &= (KVM_DIRTY_LOG_MANUAL_PROTECT_ENABLE |
  2148. KVM_DIRTY_LOG_INITIALLY_SET);
  2149. s->manual_dirty_log_protect = dirty_log_manual_caps;
  2150. if (dirty_log_manual_caps) {
  2151. ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0,
  2152. dirty_log_manual_caps);
  2153. if (ret) {
  2154. warn_report("Trying to enable capability %"PRIu64" of "
  2155. "KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2 but failed. "
  2156. "Falling back to the legacy mode. ",
  2157. dirty_log_manual_caps);
  2158. s->manual_dirty_log_protect = 0;
  2159. }
  2160. }
  2161. }
  2162. return 0;
  2163. }
  2164. static int kvm_init(MachineState *ms)
  2165. {
  2166. MachineClass *mc = MACHINE_GET_CLASS(ms);
  2167. static const char upgrade_note[] =
  2168. "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
  2169. "(see http://sourceforge.net/projects/kvm).\n";
  2170. const struct {
  2171. const char *name;
  2172. int num;
  2173. } num_cpus[] = {
  2174. { "SMP", ms->smp.cpus },
  2175. { "hotpluggable", ms->smp.max_cpus },
  2176. { /* end of list */ }
  2177. }, *nc = num_cpus;
  2178. int soft_vcpus_limit, hard_vcpus_limit;
  2179. KVMState *s;
  2180. const KVMCapabilityInfo *missing_cap;
  2181. int ret;
  2182. int type;
  2183. qemu_mutex_init(&kml_slots_lock);
  2184. s = KVM_STATE(ms->accelerator);
  2185. /*
  2186. * On systems where the kernel can support different base page
  2187. * sizes, host page size may be different from TARGET_PAGE_SIZE,
  2188. * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
  2189. * page size for the system though.
  2190. */
  2191. assert(TARGET_PAGE_SIZE <= qemu_real_host_page_size());
  2192. s->sigmask_len = 8;
  2193. accel_blocker_init();
  2194. #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
  2195. QTAILQ_INIT(&s->kvm_sw_breakpoints);
  2196. #endif
  2197. QLIST_INIT(&s->kvm_parked_vcpus);
  2198. s->fd = qemu_open_old(s->device ?: "/dev/kvm", O_RDWR);
  2199. if (s->fd == -1) {
  2200. error_report("Could not access KVM kernel module: %m");
  2201. ret = -errno;
  2202. goto err;
  2203. }
  2204. ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
  2205. if (ret < KVM_API_VERSION) {
  2206. if (ret >= 0) {
  2207. ret = -EINVAL;
  2208. }
  2209. error_report("kvm version too old");
  2210. goto err;
  2211. }
  2212. if (ret > KVM_API_VERSION) {
  2213. ret = -EINVAL;
  2214. error_report("kvm version not supported");
  2215. goto err;
  2216. }
  2217. kvm_immediate_exit = kvm_check_extension(s, KVM_CAP_IMMEDIATE_EXIT);
  2218. s->nr_slots_max = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
  2219. /* If unspecified, use the default value */
  2220. if (!s->nr_slots_max) {
  2221. s->nr_slots_max = KVM_MEMSLOTS_NR_MAX_DEFAULT;
  2222. }
  2223. type = find_kvm_machine_type(ms);
  2224. if (type < 0) {
  2225. ret = -EINVAL;
  2226. goto err;
  2227. }
  2228. ret = do_kvm_create_vm(ms, type);
  2229. if (ret < 0) {
  2230. goto err;
  2231. }
  2232. s->vmfd = ret;
  2233. s->nr_as = kvm_vm_check_extension(s, KVM_CAP_MULTI_ADDRESS_SPACE);
  2234. if (s->nr_as <= 1) {
  2235. s->nr_as = 1;
  2236. }
  2237. s->as = g_new0(struct KVMAs, s->nr_as);
  2238. /* check the vcpu limits */
  2239. soft_vcpus_limit = kvm_recommended_vcpus(s);
  2240. hard_vcpus_limit = kvm_max_vcpus(s);
  2241. while (nc->name) {
  2242. if (nc->num > soft_vcpus_limit) {
  2243. warn_report("Number of %s cpus requested (%d) exceeds "
  2244. "the recommended cpus supported by KVM (%d)",
  2245. nc->name, nc->num, soft_vcpus_limit);
  2246. if (nc->num > hard_vcpus_limit) {
  2247. error_report("Number of %s cpus requested (%d) exceeds "
  2248. "the maximum cpus supported by KVM (%d)",
  2249. nc->name, nc->num, hard_vcpus_limit);
  2250. exit(1);
  2251. }
  2252. }
  2253. nc++;
  2254. }
  2255. missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
  2256. if (!missing_cap) {
  2257. missing_cap =
  2258. kvm_check_extension_list(s, kvm_arch_required_capabilities);
  2259. }
  2260. if (missing_cap) {
  2261. ret = -EINVAL;
  2262. error_report("kvm does not support %s", missing_cap->name);
  2263. error_printf("%s", upgrade_note);
  2264. goto err;
  2265. }
  2266. s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
  2267. s->coalesced_pio = s->coalesced_mmio &&
  2268. kvm_check_extension(s, KVM_CAP_COALESCED_PIO);
  2269. ret = kvm_setup_dirty_ring(s);
  2270. if (ret < 0) {
  2271. goto err;
  2272. }
  2273. #ifdef KVM_CAP_VCPU_EVENTS
  2274. s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
  2275. #endif
  2276. s->max_nested_state_len = kvm_check_extension(s, KVM_CAP_NESTED_STATE);
  2277. s->irq_set_ioctl = KVM_IRQ_LINE;
  2278. if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
  2279. s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
  2280. }
  2281. kvm_readonly_mem_allowed =
  2282. (kvm_vm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
  2283. kvm_resamplefds_allowed =
  2284. (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
  2285. kvm_vm_attributes_allowed =
  2286. (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
  2287. #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
  2288. kvm_has_guest_debug =
  2289. (kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG) > 0);
  2290. #endif
  2291. kvm_sstep_flags = 0;
  2292. if (kvm_has_guest_debug) {
  2293. kvm_sstep_flags = SSTEP_ENABLE;
  2294. #if defined TARGET_KVM_HAVE_GUEST_DEBUG
  2295. int guest_debug_flags =
  2296. kvm_check_extension(s, KVM_CAP_SET_GUEST_DEBUG2);
  2297. if (guest_debug_flags & KVM_GUESTDBG_BLOCKIRQ) {
  2298. kvm_sstep_flags |= SSTEP_NOIRQ;
  2299. }
  2300. #endif
  2301. }
  2302. kvm_state = s;
  2303. ret = kvm_arch_init(ms, s);
  2304. if (ret < 0) {
  2305. goto err;
  2306. }
  2307. kvm_supported_memory_attributes = kvm_vm_check_extension(s, KVM_CAP_MEMORY_ATTRIBUTES);
  2308. kvm_guest_memfd_supported =
  2309. kvm_check_extension(s, KVM_CAP_GUEST_MEMFD) &&
  2310. kvm_check_extension(s, KVM_CAP_USER_MEMORY2) &&
  2311. (kvm_supported_memory_attributes & KVM_MEMORY_ATTRIBUTE_PRIVATE);
  2312. if (s->kernel_irqchip_split == ON_OFF_AUTO_AUTO) {
  2313. s->kernel_irqchip_split = mc->default_kernel_irqchip_split ? ON_OFF_AUTO_ON : ON_OFF_AUTO_OFF;
  2314. }
  2315. qemu_register_reset(kvm_unpoison_all, NULL);
  2316. if (s->kernel_irqchip_allowed) {
  2317. kvm_irqchip_create(s);
  2318. }
  2319. s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
  2320. s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
  2321. s->memory_listener.listener.coalesced_io_add = kvm_coalesce_mmio_region;
  2322. s->memory_listener.listener.coalesced_io_del = kvm_uncoalesce_mmio_region;
  2323. kvm_memory_listener_register(s, &s->memory_listener,
  2324. &address_space_memory, 0, "kvm-memory");
  2325. memory_listener_register(&kvm_io_listener,
  2326. &address_space_io);
  2327. s->sync_mmu = !!kvm_vm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
  2328. if (!s->sync_mmu) {
  2329. ret = ram_block_discard_disable(true);
  2330. assert(!ret);
  2331. }
  2332. if (s->kvm_dirty_ring_size) {
  2333. kvm_dirty_ring_reaper_init(s);
  2334. }
  2335. if (kvm_check_extension(kvm_state, KVM_CAP_BINARY_STATS_FD)) {
  2336. add_stats_callbacks(STATS_PROVIDER_KVM, query_stats_cb,
  2337. query_stats_schemas_cb);
  2338. }
  2339. return 0;
  2340. err:
  2341. assert(ret < 0);
  2342. if (s->vmfd >= 0) {
  2343. close(s->vmfd);
  2344. }
  2345. if (s->fd != -1) {
  2346. close(s->fd);
  2347. }
  2348. g_free(s->as);
  2349. g_free(s->memory_listener.slots);
  2350. return ret;
  2351. }
  2352. void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
  2353. {
  2354. s->sigmask_len = sigmask_len;
  2355. }
  2356. static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
  2357. int size, uint32_t count)
  2358. {
  2359. int i;
  2360. uint8_t *ptr = data;
  2361. for (i = 0; i < count; i++) {
  2362. address_space_rw(&address_space_io, port, attrs,
  2363. ptr, size,
  2364. direction == KVM_EXIT_IO_OUT);
  2365. ptr += size;
  2366. }
  2367. }
  2368. static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
  2369. {
  2370. int i;
  2371. fprintf(stderr, "KVM internal error. Suberror: %d\n",
  2372. run->internal.suberror);
  2373. for (i = 0; i < run->internal.ndata; ++i) {
  2374. fprintf(stderr, "extra data[%d]: 0x%016"PRIx64"\n",
  2375. i, (uint64_t)run->internal.data[i]);
  2376. }
  2377. if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
  2378. fprintf(stderr, "emulation failure\n");
  2379. if (!kvm_arch_stop_on_emulation_error(cpu)) {
  2380. cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
  2381. return EXCP_INTERRUPT;
  2382. }
  2383. }
  2384. /* FIXME: Should trigger a qmp message to let management know
  2385. * something went wrong.
  2386. */
  2387. return -1;
  2388. }
  2389. void kvm_flush_coalesced_mmio_buffer(void)
  2390. {
  2391. KVMState *s = kvm_state;
  2392. if (!s || s->coalesced_flush_in_progress) {
  2393. return;
  2394. }
  2395. s->coalesced_flush_in_progress = true;
  2396. if (s->coalesced_mmio_ring) {
  2397. struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
  2398. while (ring->first != ring->last) {
  2399. struct kvm_coalesced_mmio *ent;
  2400. ent = &ring->coalesced_mmio[ring->first];
  2401. if (ent->pio == 1) {
  2402. address_space_write(&address_space_io, ent->phys_addr,
  2403. MEMTXATTRS_UNSPECIFIED, ent->data,
  2404. ent->len);
  2405. } else {
  2406. cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
  2407. }
  2408. smp_wmb();
  2409. ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
  2410. }
  2411. }
  2412. s->coalesced_flush_in_progress = false;
  2413. }
  2414. static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
  2415. {
  2416. if (!cpu->vcpu_dirty && !kvm_state->guest_state_protected) {
  2417. Error *err = NULL;
  2418. int ret = kvm_arch_get_registers(cpu, &err);
  2419. if (ret) {
  2420. if (err) {
  2421. error_reportf_err(err, "Failed to synchronize CPU state: ");
  2422. } else {
  2423. error_report("Failed to get registers: %s", strerror(-ret));
  2424. }
  2425. cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
  2426. vm_stop(RUN_STATE_INTERNAL_ERROR);
  2427. }
  2428. cpu->vcpu_dirty = true;
  2429. }
  2430. }
  2431. void kvm_cpu_synchronize_state(CPUState *cpu)
  2432. {
  2433. if (!cpu->vcpu_dirty && !kvm_state->guest_state_protected) {
  2434. run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
  2435. }
  2436. }
  2437. static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
  2438. {
  2439. Error *err = NULL;
  2440. int ret = kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE, &err);
  2441. if (ret) {
  2442. if (err) {
  2443. error_reportf_err(err, "Restoring resisters after reset: ");
  2444. } else {
  2445. error_report("Failed to put registers after reset: %s",
  2446. strerror(-ret));
  2447. }
  2448. cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
  2449. vm_stop(RUN_STATE_INTERNAL_ERROR);
  2450. }
  2451. cpu->vcpu_dirty = false;
  2452. }
  2453. void kvm_cpu_synchronize_post_reset(CPUState *cpu)
  2454. {
  2455. run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
  2456. if (cpu == first_cpu) {
  2457. kvm_reset_parked_vcpus(kvm_state);
  2458. }
  2459. }
  2460. static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
  2461. {
  2462. Error *err = NULL;
  2463. int ret = kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE, &err);
  2464. if (ret) {
  2465. if (err) {
  2466. error_reportf_err(err, "Putting registers after init: ");
  2467. } else {
  2468. error_report("Failed to put registers after init: %s",
  2469. strerror(-ret));
  2470. }
  2471. exit(1);
  2472. }
  2473. cpu->vcpu_dirty = false;
  2474. }
  2475. void kvm_cpu_synchronize_post_init(CPUState *cpu)
  2476. {
  2477. if (!kvm_state->guest_state_protected) {
  2478. /*
  2479. * This runs before the machine_init_done notifiers, and is the last
  2480. * opportunity to synchronize the state of confidential guests.
  2481. */
  2482. run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
  2483. }
  2484. }
  2485. static void do_kvm_cpu_synchronize_pre_loadvm(CPUState *cpu, run_on_cpu_data arg)
  2486. {
  2487. cpu->vcpu_dirty = true;
  2488. }
  2489. void kvm_cpu_synchronize_pre_loadvm(CPUState *cpu)
  2490. {
  2491. run_on_cpu(cpu, do_kvm_cpu_synchronize_pre_loadvm, RUN_ON_CPU_NULL);
  2492. }
  2493. #ifdef KVM_HAVE_MCE_INJECTION
  2494. static __thread void *pending_sigbus_addr;
  2495. static __thread int pending_sigbus_code;
  2496. static __thread bool have_sigbus_pending;
  2497. #endif
  2498. static void kvm_cpu_kick(CPUState *cpu)
  2499. {
  2500. qatomic_set(&cpu->kvm_run->immediate_exit, 1);
  2501. }
  2502. static void kvm_cpu_kick_self(void)
  2503. {
  2504. if (kvm_immediate_exit) {
  2505. kvm_cpu_kick(current_cpu);
  2506. } else {
  2507. qemu_cpu_kick_self();
  2508. }
  2509. }
  2510. static void kvm_eat_signals(CPUState *cpu)
  2511. {
  2512. struct timespec ts = { 0, 0 };
  2513. siginfo_t siginfo;
  2514. sigset_t waitset;
  2515. sigset_t chkset;
  2516. int r;
  2517. if (kvm_immediate_exit) {
  2518. qatomic_set(&cpu->kvm_run->immediate_exit, 0);
  2519. /* Write kvm_run->immediate_exit before the cpu->exit_request
  2520. * write in kvm_cpu_exec.
  2521. */
  2522. smp_wmb();
  2523. return;
  2524. }
  2525. sigemptyset(&waitset);
  2526. sigaddset(&waitset, SIG_IPI);
  2527. do {
  2528. r = sigtimedwait(&waitset, &siginfo, &ts);
  2529. if (r == -1 && !(errno == EAGAIN || errno == EINTR)) {
  2530. perror("sigtimedwait");
  2531. exit(1);
  2532. }
  2533. r = sigpending(&chkset);
  2534. if (r == -1) {
  2535. perror("sigpending");
  2536. exit(1);
  2537. }
  2538. } while (sigismember(&chkset, SIG_IPI));
  2539. }
  2540. int kvm_convert_memory(hwaddr start, hwaddr size, bool to_private)
  2541. {
  2542. MemoryRegionSection section;
  2543. ram_addr_t offset;
  2544. MemoryRegion *mr;
  2545. RAMBlock *rb;
  2546. void *addr;
  2547. int ret = -EINVAL;
  2548. trace_kvm_convert_memory(start, size, to_private ? "shared_to_private" : "private_to_shared");
  2549. if (!QEMU_PTR_IS_ALIGNED(start, qemu_real_host_page_size()) ||
  2550. !QEMU_PTR_IS_ALIGNED(size, qemu_real_host_page_size())) {
  2551. return ret;
  2552. }
  2553. if (!size) {
  2554. return ret;
  2555. }
  2556. section = memory_region_find(get_system_memory(), start, size);
  2557. mr = section.mr;
  2558. if (!mr) {
  2559. /*
  2560. * Ignore converting non-assigned region to shared.
  2561. *
  2562. * TDX requires vMMIO region to be shared to inject #VE to guest.
  2563. * OVMF issues conservatively MapGPA(shared) on 32bit PCI MMIO region,
  2564. * and vIO-APIC 0xFEC00000 4K page.
  2565. * OVMF assigns 32bit PCI MMIO region to
  2566. * [top of low memory: typically 2GB=0xC000000, 0xFC00000)
  2567. */
  2568. if (!to_private) {
  2569. return 0;
  2570. }
  2571. return ret;
  2572. }
  2573. if (!memory_region_has_guest_memfd(mr)) {
  2574. /*
  2575. * Because vMMIO region must be shared, guest TD may convert vMMIO
  2576. * region to shared explicitly. Don't complain such case. See
  2577. * memory_region_type() for checking if the region is MMIO region.
  2578. */
  2579. if (!to_private &&
  2580. !memory_region_is_ram(mr) &&
  2581. !memory_region_is_ram_device(mr) &&
  2582. !memory_region_is_rom(mr) &&
  2583. !memory_region_is_romd(mr)) {
  2584. ret = 0;
  2585. } else {
  2586. error_report("Convert non guest_memfd backed memory region "
  2587. "(0x%"HWADDR_PRIx" ,+ 0x%"HWADDR_PRIx") to %s",
  2588. start, size, to_private ? "private" : "shared");
  2589. }
  2590. goto out_unref;
  2591. }
  2592. if (to_private) {
  2593. ret = kvm_set_memory_attributes_private(start, size);
  2594. } else {
  2595. ret = kvm_set_memory_attributes_shared(start, size);
  2596. }
  2597. if (ret) {
  2598. goto out_unref;
  2599. }
  2600. addr = memory_region_get_ram_ptr(mr) + section.offset_within_region;
  2601. rb = qemu_ram_block_from_host(addr, false, &offset);
  2602. if (to_private) {
  2603. if (rb->page_size != qemu_real_host_page_size()) {
  2604. /*
  2605. * shared memory is backed by hugetlb, which is supposed to be
  2606. * pre-allocated and doesn't need to be discarded
  2607. */
  2608. goto out_unref;
  2609. }
  2610. ret = ram_block_discard_range(rb, offset, size);
  2611. } else {
  2612. ret = ram_block_discard_guest_memfd_range(rb, offset, size);
  2613. }
  2614. out_unref:
  2615. memory_region_unref(mr);
  2616. return ret;
  2617. }
  2618. int kvm_cpu_exec(CPUState *cpu)
  2619. {
  2620. struct kvm_run *run = cpu->kvm_run;
  2621. int ret, run_ret;
  2622. trace_kvm_cpu_exec();
  2623. if (kvm_arch_process_async_events(cpu)) {
  2624. qatomic_set(&cpu->exit_request, 0);
  2625. return EXCP_HLT;
  2626. }
  2627. bql_unlock();
  2628. cpu_exec_start(cpu);
  2629. do {
  2630. MemTxAttrs attrs;
  2631. if (cpu->vcpu_dirty) {
  2632. Error *err = NULL;
  2633. ret = kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE, &err);
  2634. if (ret) {
  2635. if (err) {
  2636. error_reportf_err(err, "Putting registers after init: ");
  2637. } else {
  2638. error_report("Failed to put registers after init: %s",
  2639. strerror(-ret));
  2640. }
  2641. ret = -1;
  2642. break;
  2643. }
  2644. cpu->vcpu_dirty = false;
  2645. }
  2646. kvm_arch_pre_run(cpu, run);
  2647. if (qatomic_read(&cpu->exit_request)) {
  2648. trace_kvm_interrupt_exit_request();
  2649. /*
  2650. * KVM requires us to reenter the kernel after IO exits to complete
  2651. * instruction emulation. This self-signal will ensure that we
  2652. * leave ASAP again.
  2653. */
  2654. kvm_cpu_kick_self();
  2655. }
  2656. /* Read cpu->exit_request before KVM_RUN reads run->immediate_exit.
  2657. * Matching barrier in kvm_eat_signals.
  2658. */
  2659. smp_rmb();
  2660. run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
  2661. attrs = kvm_arch_post_run(cpu, run);
  2662. #ifdef KVM_HAVE_MCE_INJECTION
  2663. if (unlikely(have_sigbus_pending)) {
  2664. bql_lock();
  2665. kvm_arch_on_sigbus_vcpu(cpu, pending_sigbus_code,
  2666. pending_sigbus_addr);
  2667. have_sigbus_pending = false;
  2668. bql_unlock();
  2669. }
  2670. #endif
  2671. if (run_ret < 0) {
  2672. if (run_ret == -EINTR || run_ret == -EAGAIN) {
  2673. trace_kvm_io_window_exit();
  2674. kvm_eat_signals(cpu);
  2675. ret = EXCP_INTERRUPT;
  2676. break;
  2677. }
  2678. if (!(run_ret == -EFAULT && run->exit_reason == KVM_EXIT_MEMORY_FAULT)) {
  2679. fprintf(stderr, "error: kvm run failed %s\n",
  2680. strerror(-run_ret));
  2681. #ifdef TARGET_PPC
  2682. if (run_ret == -EBUSY) {
  2683. fprintf(stderr,
  2684. "This is probably because your SMT is enabled.\n"
  2685. "VCPU can only run on primary threads with all "
  2686. "secondary threads offline.\n");
  2687. }
  2688. #endif
  2689. ret = -1;
  2690. break;
  2691. }
  2692. }
  2693. trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
  2694. switch (run->exit_reason) {
  2695. case KVM_EXIT_IO:
  2696. /* Called outside BQL */
  2697. kvm_handle_io(run->io.port, attrs,
  2698. (uint8_t *)run + run->io.data_offset,
  2699. run->io.direction,
  2700. run->io.size,
  2701. run->io.count);
  2702. ret = 0;
  2703. break;
  2704. case KVM_EXIT_MMIO:
  2705. /* Called outside BQL */
  2706. address_space_rw(&address_space_memory,
  2707. run->mmio.phys_addr, attrs,
  2708. run->mmio.data,
  2709. run->mmio.len,
  2710. run->mmio.is_write);
  2711. ret = 0;
  2712. break;
  2713. case KVM_EXIT_IRQ_WINDOW_OPEN:
  2714. ret = EXCP_INTERRUPT;
  2715. break;
  2716. case KVM_EXIT_SHUTDOWN:
  2717. qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
  2718. ret = EXCP_INTERRUPT;
  2719. break;
  2720. case KVM_EXIT_UNKNOWN:
  2721. fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
  2722. (uint64_t)run->hw.hardware_exit_reason);
  2723. ret = -1;
  2724. break;
  2725. case KVM_EXIT_INTERNAL_ERROR:
  2726. ret = kvm_handle_internal_error(cpu, run);
  2727. break;
  2728. case KVM_EXIT_DIRTY_RING_FULL:
  2729. /*
  2730. * We shouldn't continue if the dirty ring of this vcpu is
  2731. * still full. Got kicked by KVM_RESET_DIRTY_RINGS.
  2732. */
  2733. trace_kvm_dirty_ring_full(cpu->cpu_index);
  2734. bql_lock();
  2735. /*
  2736. * We throttle vCPU by making it sleep once it exit from kernel
  2737. * due to dirty ring full. In the dirtylimit scenario, reaping
  2738. * all vCPUs after a single vCPU dirty ring get full result in
  2739. * the miss of sleep, so just reap the ring-fulled vCPU.
  2740. */
  2741. if (dirtylimit_in_service()) {
  2742. kvm_dirty_ring_reap(kvm_state, cpu);
  2743. } else {
  2744. kvm_dirty_ring_reap(kvm_state, NULL);
  2745. }
  2746. bql_unlock();
  2747. dirtylimit_vcpu_execute(cpu);
  2748. ret = 0;
  2749. break;
  2750. case KVM_EXIT_SYSTEM_EVENT:
  2751. trace_kvm_run_exit_system_event(cpu->cpu_index, run->system_event.type);
  2752. switch (run->system_event.type) {
  2753. case KVM_SYSTEM_EVENT_SHUTDOWN:
  2754. qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
  2755. ret = EXCP_INTERRUPT;
  2756. break;
  2757. case KVM_SYSTEM_EVENT_RESET:
  2758. qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
  2759. ret = EXCP_INTERRUPT;
  2760. break;
  2761. case KVM_SYSTEM_EVENT_CRASH:
  2762. kvm_cpu_synchronize_state(cpu);
  2763. bql_lock();
  2764. qemu_system_guest_panicked(cpu_get_crash_info(cpu));
  2765. bql_unlock();
  2766. ret = 0;
  2767. break;
  2768. default:
  2769. ret = kvm_arch_handle_exit(cpu, run);
  2770. break;
  2771. }
  2772. break;
  2773. case KVM_EXIT_MEMORY_FAULT:
  2774. trace_kvm_memory_fault(run->memory_fault.gpa,
  2775. run->memory_fault.size,
  2776. run->memory_fault.flags);
  2777. if (run->memory_fault.flags & ~KVM_MEMORY_EXIT_FLAG_PRIVATE) {
  2778. error_report("KVM_EXIT_MEMORY_FAULT: Unknown flag 0x%" PRIx64,
  2779. (uint64_t)run->memory_fault.flags);
  2780. ret = -1;
  2781. break;
  2782. }
  2783. ret = kvm_convert_memory(run->memory_fault.gpa, run->memory_fault.size,
  2784. run->memory_fault.flags & KVM_MEMORY_EXIT_FLAG_PRIVATE);
  2785. break;
  2786. default:
  2787. ret = kvm_arch_handle_exit(cpu, run);
  2788. break;
  2789. }
  2790. } while (ret == 0);
  2791. cpu_exec_end(cpu);
  2792. bql_lock();
  2793. if (ret < 0) {
  2794. cpu_dump_state(cpu, stderr, CPU_DUMP_CODE);
  2795. vm_stop(RUN_STATE_INTERNAL_ERROR);
  2796. }
  2797. qatomic_set(&cpu->exit_request, 0);
  2798. return ret;
  2799. }
  2800. int kvm_ioctl(KVMState *s, unsigned long type, ...)
  2801. {
  2802. int ret;
  2803. void *arg;
  2804. va_list ap;
  2805. va_start(ap, type);
  2806. arg = va_arg(ap, void *);
  2807. va_end(ap);
  2808. trace_kvm_ioctl(type, arg);
  2809. ret = ioctl(s->fd, type, arg);
  2810. if (ret == -1) {
  2811. ret = -errno;
  2812. }
  2813. return ret;
  2814. }
  2815. int kvm_vm_ioctl(KVMState *s, unsigned long type, ...)
  2816. {
  2817. int ret;
  2818. void *arg;
  2819. va_list ap;
  2820. va_start(ap, type);
  2821. arg = va_arg(ap, void *);
  2822. va_end(ap);
  2823. trace_kvm_vm_ioctl(type, arg);
  2824. accel_ioctl_begin();
  2825. ret = ioctl(s->vmfd, type, arg);
  2826. accel_ioctl_end();
  2827. if (ret == -1) {
  2828. ret = -errno;
  2829. }
  2830. return ret;
  2831. }
  2832. int kvm_vcpu_ioctl(CPUState *cpu, unsigned long type, ...)
  2833. {
  2834. int ret;
  2835. void *arg;
  2836. va_list ap;
  2837. va_start(ap, type);
  2838. arg = va_arg(ap, void *);
  2839. va_end(ap);
  2840. trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
  2841. accel_cpu_ioctl_begin(cpu);
  2842. ret = ioctl(cpu->kvm_fd, type, arg);
  2843. accel_cpu_ioctl_end(cpu);
  2844. if (ret == -1) {
  2845. ret = -errno;
  2846. }
  2847. return ret;
  2848. }
  2849. int kvm_device_ioctl(int fd, unsigned long type, ...)
  2850. {
  2851. int ret;
  2852. void *arg;
  2853. va_list ap;
  2854. va_start(ap, type);
  2855. arg = va_arg(ap, void *);
  2856. va_end(ap);
  2857. trace_kvm_device_ioctl(fd, type, arg);
  2858. accel_ioctl_begin();
  2859. ret = ioctl(fd, type, arg);
  2860. accel_ioctl_end();
  2861. if (ret == -1) {
  2862. ret = -errno;
  2863. }
  2864. return ret;
  2865. }
  2866. int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
  2867. {
  2868. int ret;
  2869. struct kvm_device_attr attribute = {
  2870. .group = group,
  2871. .attr = attr,
  2872. };
  2873. if (!kvm_vm_attributes_allowed) {
  2874. return 0;
  2875. }
  2876. ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
  2877. /* kvm returns 0 on success for HAS_DEVICE_ATTR */
  2878. return ret ? 0 : 1;
  2879. }
  2880. int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
  2881. {
  2882. struct kvm_device_attr attribute = {
  2883. .group = group,
  2884. .attr = attr,
  2885. .flags = 0,
  2886. };
  2887. return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
  2888. }
  2889. int kvm_device_access(int fd, int group, uint64_t attr,
  2890. void *val, bool write, Error **errp)
  2891. {
  2892. struct kvm_device_attr kvmattr;
  2893. int err;
  2894. kvmattr.flags = 0;
  2895. kvmattr.group = group;
  2896. kvmattr.attr = attr;
  2897. kvmattr.addr = (uintptr_t)val;
  2898. err = kvm_device_ioctl(fd,
  2899. write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
  2900. &kvmattr);
  2901. if (err < 0) {
  2902. error_setg_errno(errp, -err,
  2903. "KVM_%s_DEVICE_ATTR failed: Group %d "
  2904. "attr 0x%016" PRIx64,
  2905. write ? "SET" : "GET", group, attr);
  2906. }
  2907. return err;
  2908. }
  2909. bool kvm_has_sync_mmu(void)
  2910. {
  2911. return kvm_state->sync_mmu;
  2912. }
  2913. int kvm_has_vcpu_events(void)
  2914. {
  2915. return kvm_state->vcpu_events;
  2916. }
  2917. int kvm_max_nested_state_length(void)
  2918. {
  2919. return kvm_state->max_nested_state_len;
  2920. }
  2921. int kvm_has_gsi_routing(void)
  2922. {
  2923. #ifdef KVM_CAP_IRQ_ROUTING
  2924. return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
  2925. #else
  2926. return false;
  2927. #endif
  2928. }
  2929. bool kvm_arm_supports_user_irq(void)
  2930. {
  2931. return kvm_check_extension(kvm_state, KVM_CAP_ARM_USER_IRQ);
  2932. }
  2933. #ifdef TARGET_KVM_HAVE_GUEST_DEBUG
  2934. struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu, vaddr pc)
  2935. {
  2936. struct kvm_sw_breakpoint *bp;
  2937. QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
  2938. if (bp->pc == pc) {
  2939. return bp;
  2940. }
  2941. }
  2942. return NULL;
  2943. }
  2944. int kvm_sw_breakpoints_active(CPUState *cpu)
  2945. {
  2946. return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
  2947. }
  2948. struct kvm_set_guest_debug_data {
  2949. struct kvm_guest_debug dbg;
  2950. int err;
  2951. };
  2952. static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
  2953. {
  2954. struct kvm_set_guest_debug_data *dbg_data =
  2955. (struct kvm_set_guest_debug_data *) data.host_ptr;
  2956. dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
  2957. &dbg_data->dbg);
  2958. }
  2959. int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
  2960. {
  2961. struct kvm_set_guest_debug_data data;
  2962. data.dbg.control = reinject_trap;
  2963. if (cpu->singlestep_enabled) {
  2964. data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
  2965. if (cpu->singlestep_enabled & SSTEP_NOIRQ) {
  2966. data.dbg.control |= KVM_GUESTDBG_BLOCKIRQ;
  2967. }
  2968. }
  2969. kvm_arch_update_guest_debug(cpu, &data.dbg);
  2970. run_on_cpu(cpu, kvm_invoke_set_guest_debug,
  2971. RUN_ON_CPU_HOST_PTR(&data));
  2972. return data.err;
  2973. }
  2974. bool kvm_supports_guest_debug(void)
  2975. {
  2976. /* probed during kvm_init() */
  2977. return kvm_has_guest_debug;
  2978. }
  2979. int kvm_insert_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
  2980. {
  2981. struct kvm_sw_breakpoint *bp;
  2982. int err;
  2983. if (type == GDB_BREAKPOINT_SW) {
  2984. bp = kvm_find_sw_breakpoint(cpu, addr);
  2985. if (bp) {
  2986. bp->use_count++;
  2987. return 0;
  2988. }
  2989. bp = g_new(struct kvm_sw_breakpoint, 1);
  2990. bp->pc = addr;
  2991. bp->use_count = 1;
  2992. err = kvm_arch_insert_sw_breakpoint(cpu, bp);
  2993. if (err) {
  2994. g_free(bp);
  2995. return err;
  2996. }
  2997. QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
  2998. } else {
  2999. err = kvm_arch_insert_hw_breakpoint(addr, len, type);
  3000. if (err) {
  3001. return err;
  3002. }
  3003. }
  3004. CPU_FOREACH(cpu) {
  3005. err = kvm_update_guest_debug(cpu, 0);
  3006. if (err) {
  3007. return err;
  3008. }
  3009. }
  3010. return 0;
  3011. }
  3012. int kvm_remove_breakpoint(CPUState *cpu, int type, vaddr addr, vaddr len)
  3013. {
  3014. struct kvm_sw_breakpoint *bp;
  3015. int err;
  3016. if (type == GDB_BREAKPOINT_SW) {
  3017. bp = kvm_find_sw_breakpoint(cpu, addr);
  3018. if (!bp) {
  3019. return -ENOENT;
  3020. }
  3021. if (bp->use_count > 1) {
  3022. bp->use_count--;
  3023. return 0;
  3024. }
  3025. err = kvm_arch_remove_sw_breakpoint(cpu, bp);
  3026. if (err) {
  3027. return err;
  3028. }
  3029. QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
  3030. g_free(bp);
  3031. } else {
  3032. err = kvm_arch_remove_hw_breakpoint(addr, len, type);
  3033. if (err) {
  3034. return err;
  3035. }
  3036. }
  3037. CPU_FOREACH(cpu) {
  3038. err = kvm_update_guest_debug(cpu, 0);
  3039. if (err) {
  3040. return err;
  3041. }
  3042. }
  3043. return 0;
  3044. }
  3045. void kvm_remove_all_breakpoints(CPUState *cpu)
  3046. {
  3047. struct kvm_sw_breakpoint *bp, *next;
  3048. KVMState *s = cpu->kvm_state;
  3049. CPUState *tmpcpu;
  3050. QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
  3051. if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
  3052. /* Try harder to find a CPU that currently sees the breakpoint. */
  3053. CPU_FOREACH(tmpcpu) {
  3054. if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
  3055. break;
  3056. }
  3057. }
  3058. }
  3059. QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
  3060. g_free(bp);
  3061. }
  3062. kvm_arch_remove_all_hw_breakpoints();
  3063. CPU_FOREACH(cpu) {
  3064. kvm_update_guest_debug(cpu, 0);
  3065. }
  3066. }
  3067. #endif /* !TARGET_KVM_HAVE_GUEST_DEBUG */
  3068. static int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
  3069. {
  3070. KVMState *s = kvm_state;
  3071. struct kvm_signal_mask *sigmask;
  3072. int r;
  3073. sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
  3074. sigmask->len = s->sigmask_len;
  3075. memcpy(sigmask->sigset, sigset, sizeof(*sigset));
  3076. r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
  3077. g_free(sigmask);
  3078. return r;
  3079. }
  3080. static void kvm_ipi_signal(int sig)
  3081. {
  3082. if (current_cpu) {
  3083. assert(kvm_immediate_exit);
  3084. kvm_cpu_kick(current_cpu);
  3085. }
  3086. }
  3087. void kvm_init_cpu_signals(CPUState *cpu)
  3088. {
  3089. int r;
  3090. sigset_t set;
  3091. struct sigaction sigact;
  3092. memset(&sigact, 0, sizeof(sigact));
  3093. sigact.sa_handler = kvm_ipi_signal;
  3094. sigaction(SIG_IPI, &sigact, NULL);
  3095. pthread_sigmask(SIG_BLOCK, NULL, &set);
  3096. #if defined KVM_HAVE_MCE_INJECTION
  3097. sigdelset(&set, SIGBUS);
  3098. pthread_sigmask(SIG_SETMASK, &set, NULL);
  3099. #endif
  3100. sigdelset(&set, SIG_IPI);
  3101. if (kvm_immediate_exit) {
  3102. r = pthread_sigmask(SIG_SETMASK, &set, NULL);
  3103. } else {
  3104. r = kvm_set_signal_mask(cpu, &set);
  3105. }
  3106. if (r) {
  3107. fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));
  3108. exit(1);
  3109. }
  3110. }
  3111. /* Called asynchronously in VCPU thread. */
  3112. int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
  3113. {
  3114. #ifdef KVM_HAVE_MCE_INJECTION
  3115. if (have_sigbus_pending) {
  3116. return 1;
  3117. }
  3118. have_sigbus_pending = true;
  3119. pending_sigbus_addr = addr;
  3120. pending_sigbus_code = code;
  3121. qatomic_set(&cpu->exit_request, 1);
  3122. return 0;
  3123. #else
  3124. return 1;
  3125. #endif
  3126. }
  3127. /* Called synchronously (via signalfd) in main thread. */
  3128. int kvm_on_sigbus(int code, void *addr)
  3129. {
  3130. #ifdef KVM_HAVE_MCE_INJECTION
  3131. /* Action required MCE kills the process if SIGBUS is blocked. Because
  3132. * that's what happens in the I/O thread, where we handle MCE via signalfd,
  3133. * we can only get action optional here.
  3134. */
  3135. assert(code != BUS_MCEERR_AR);
  3136. kvm_arch_on_sigbus_vcpu(first_cpu, code, addr);
  3137. return 0;
  3138. #else
  3139. return 1;
  3140. #endif
  3141. }
  3142. int kvm_create_device(KVMState *s, uint64_t type, bool test)
  3143. {
  3144. int ret;
  3145. struct kvm_create_device create_dev;
  3146. create_dev.type = type;
  3147. create_dev.fd = -1;
  3148. create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
  3149. if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
  3150. return -ENOTSUP;
  3151. }
  3152. ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
  3153. if (ret) {
  3154. return ret;
  3155. }
  3156. return test ? 0 : create_dev.fd;
  3157. }
  3158. bool kvm_device_supported(int vmfd, uint64_t type)
  3159. {
  3160. struct kvm_create_device create_dev = {
  3161. .type = type,
  3162. .fd = -1,
  3163. .flags = KVM_CREATE_DEVICE_TEST,
  3164. };
  3165. if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
  3166. return false;
  3167. }
  3168. return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
  3169. }
  3170. int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
  3171. {
  3172. struct kvm_one_reg reg;
  3173. int r;
  3174. reg.id = id;
  3175. reg.addr = (uintptr_t) source;
  3176. r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
  3177. if (r) {
  3178. trace_kvm_failed_reg_set(id, strerror(-r));
  3179. }
  3180. return r;
  3181. }
  3182. int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
  3183. {
  3184. struct kvm_one_reg reg;
  3185. int r;
  3186. reg.id = id;
  3187. reg.addr = (uintptr_t) target;
  3188. r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
  3189. if (r) {
  3190. trace_kvm_failed_reg_get(id, strerror(-r));
  3191. }
  3192. return r;
  3193. }
  3194. static bool kvm_accel_has_memory(MachineState *ms, AddressSpace *as,
  3195. hwaddr start_addr, hwaddr size)
  3196. {
  3197. KVMState *kvm = KVM_STATE(ms->accelerator);
  3198. int i;
  3199. for (i = 0; i < kvm->nr_as; ++i) {
  3200. if (kvm->as[i].as == as && kvm->as[i].ml) {
  3201. size = MIN(kvm_max_slot_size, size);
  3202. return NULL != kvm_lookup_matching_slot(kvm->as[i].ml,
  3203. start_addr, size);
  3204. }
  3205. }
  3206. return false;
  3207. }
  3208. static void kvm_get_kvm_shadow_mem(Object *obj, Visitor *v,
  3209. const char *name, void *opaque,
  3210. Error **errp)
  3211. {
  3212. KVMState *s = KVM_STATE(obj);
  3213. int64_t value = s->kvm_shadow_mem;
  3214. visit_type_int(v, name, &value, errp);
  3215. }
  3216. static void kvm_set_kvm_shadow_mem(Object *obj, Visitor *v,
  3217. const char *name, void *opaque,
  3218. Error **errp)
  3219. {
  3220. KVMState *s = KVM_STATE(obj);
  3221. int64_t value;
  3222. if (s->fd != -1) {
  3223. error_setg(errp, "Cannot set properties after the accelerator has been initialized");
  3224. return;
  3225. }
  3226. if (!visit_type_int(v, name, &value, errp)) {
  3227. return;
  3228. }
  3229. s->kvm_shadow_mem = value;
  3230. }
  3231. static void kvm_set_kernel_irqchip(Object *obj, Visitor *v,
  3232. const char *name, void *opaque,
  3233. Error **errp)
  3234. {
  3235. KVMState *s = KVM_STATE(obj);
  3236. OnOffSplit mode;
  3237. if (s->fd != -1) {
  3238. error_setg(errp, "Cannot set properties after the accelerator has been initialized");
  3239. return;
  3240. }
  3241. if (!visit_type_OnOffSplit(v, name, &mode, errp)) {
  3242. return;
  3243. }
  3244. switch (mode) {
  3245. case ON_OFF_SPLIT_ON:
  3246. s->kernel_irqchip_allowed = true;
  3247. s->kernel_irqchip_required = true;
  3248. s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
  3249. break;
  3250. case ON_OFF_SPLIT_OFF:
  3251. s->kernel_irqchip_allowed = false;
  3252. s->kernel_irqchip_required = false;
  3253. s->kernel_irqchip_split = ON_OFF_AUTO_OFF;
  3254. break;
  3255. case ON_OFF_SPLIT_SPLIT:
  3256. s->kernel_irqchip_allowed = true;
  3257. s->kernel_irqchip_required = true;
  3258. s->kernel_irqchip_split = ON_OFF_AUTO_ON;
  3259. break;
  3260. default:
  3261. /* The value was checked in visit_type_OnOffSplit() above. If
  3262. * we get here, then something is wrong in QEMU.
  3263. */
  3264. abort();
  3265. }
  3266. }
  3267. bool kvm_kernel_irqchip_allowed(void)
  3268. {
  3269. return kvm_state->kernel_irqchip_allowed;
  3270. }
  3271. bool kvm_kernel_irqchip_required(void)
  3272. {
  3273. return kvm_state->kernel_irqchip_required;
  3274. }
  3275. bool kvm_kernel_irqchip_split(void)
  3276. {
  3277. return kvm_state->kernel_irqchip_split == ON_OFF_AUTO_ON;
  3278. }
  3279. static void kvm_get_dirty_ring_size(Object *obj, Visitor *v,
  3280. const char *name, void *opaque,
  3281. Error **errp)
  3282. {
  3283. KVMState *s = KVM_STATE(obj);
  3284. uint32_t value = s->kvm_dirty_ring_size;
  3285. visit_type_uint32(v, name, &value, errp);
  3286. }
  3287. static void kvm_set_dirty_ring_size(Object *obj, Visitor *v,
  3288. const char *name, void *opaque,
  3289. Error **errp)
  3290. {
  3291. KVMState *s = KVM_STATE(obj);
  3292. uint32_t value;
  3293. if (s->fd != -1) {
  3294. error_setg(errp, "Cannot set properties after the accelerator has been initialized");
  3295. return;
  3296. }
  3297. if (!visit_type_uint32(v, name, &value, errp)) {
  3298. return;
  3299. }
  3300. if (value & (value - 1)) {
  3301. error_setg(errp, "dirty-ring-size must be a power of two.");
  3302. return;
  3303. }
  3304. s->kvm_dirty_ring_size = value;
  3305. }
  3306. static char *kvm_get_device(Object *obj,
  3307. Error **errp G_GNUC_UNUSED)
  3308. {
  3309. KVMState *s = KVM_STATE(obj);
  3310. return g_strdup(s->device);
  3311. }
  3312. static void kvm_set_device(Object *obj,
  3313. const char *value,
  3314. Error **errp G_GNUC_UNUSED)
  3315. {
  3316. KVMState *s = KVM_STATE(obj);
  3317. g_free(s->device);
  3318. s->device = g_strdup(value);
  3319. }
  3320. static void kvm_set_kvm_rapl(Object *obj, bool value, Error **errp)
  3321. {
  3322. KVMState *s = KVM_STATE(obj);
  3323. s->msr_energy.enable = value;
  3324. }
  3325. static void kvm_set_kvm_rapl_socket_path(Object *obj,
  3326. const char *str,
  3327. Error **errp)
  3328. {
  3329. KVMState *s = KVM_STATE(obj);
  3330. g_free(s->msr_energy.socket_path);
  3331. s->msr_energy.socket_path = g_strdup(str);
  3332. }
  3333. static void kvm_accel_instance_init(Object *obj)
  3334. {
  3335. KVMState *s = KVM_STATE(obj);
  3336. s->fd = -1;
  3337. s->vmfd = -1;
  3338. s->kvm_shadow_mem = -1;
  3339. s->kernel_irqchip_allowed = true;
  3340. s->kernel_irqchip_split = ON_OFF_AUTO_AUTO;
  3341. /* KVM dirty ring is by default off */
  3342. s->kvm_dirty_ring_size = 0;
  3343. s->kvm_dirty_ring_with_bitmap = false;
  3344. s->kvm_eager_split_size = 0;
  3345. s->notify_vmexit = NOTIFY_VMEXIT_OPTION_RUN;
  3346. s->notify_window = 0;
  3347. s->xen_version = 0;
  3348. s->xen_gnttab_max_frames = 64;
  3349. s->xen_evtchn_max_pirq = 256;
  3350. s->device = NULL;
  3351. s->msr_energy.enable = false;
  3352. }
  3353. /**
  3354. * kvm_gdbstub_sstep_flags():
  3355. *
  3356. * Returns: SSTEP_* flags that KVM supports for guest debug. The
  3357. * support is probed during kvm_init()
  3358. */
  3359. static int kvm_gdbstub_sstep_flags(void)
  3360. {
  3361. return kvm_sstep_flags;
  3362. }
  3363. static void kvm_accel_class_init(ObjectClass *oc, void *data)
  3364. {
  3365. AccelClass *ac = ACCEL_CLASS(oc);
  3366. ac->name = "KVM";
  3367. ac->init_machine = kvm_init;
  3368. ac->has_memory = kvm_accel_has_memory;
  3369. ac->allowed = &kvm_allowed;
  3370. ac->gdbstub_supported_sstep_flags = kvm_gdbstub_sstep_flags;
  3371. object_class_property_add(oc, "kernel-irqchip", "on|off|split",
  3372. NULL, kvm_set_kernel_irqchip,
  3373. NULL, NULL);
  3374. object_class_property_set_description(oc, "kernel-irqchip",
  3375. "Configure KVM in-kernel irqchip");
  3376. object_class_property_add(oc, "kvm-shadow-mem", "int",
  3377. kvm_get_kvm_shadow_mem, kvm_set_kvm_shadow_mem,
  3378. NULL, NULL);
  3379. object_class_property_set_description(oc, "kvm-shadow-mem",
  3380. "KVM shadow MMU size");
  3381. object_class_property_add(oc, "dirty-ring-size", "uint32",
  3382. kvm_get_dirty_ring_size, kvm_set_dirty_ring_size,
  3383. NULL, NULL);
  3384. object_class_property_set_description(oc, "dirty-ring-size",
  3385. "Size of KVM dirty page ring buffer (default: 0, i.e. use bitmap)");
  3386. object_class_property_add_str(oc, "device", kvm_get_device, kvm_set_device);
  3387. object_class_property_set_description(oc, "device",
  3388. "Path to the device node to use (default: /dev/kvm)");
  3389. object_class_property_add_bool(oc, "rapl",
  3390. NULL,
  3391. kvm_set_kvm_rapl);
  3392. object_class_property_set_description(oc, "rapl",
  3393. "Allow energy related MSRs for RAPL interface in Guest");
  3394. object_class_property_add_str(oc, "rapl-helper-socket", NULL,
  3395. kvm_set_kvm_rapl_socket_path);
  3396. object_class_property_set_description(oc, "rapl-helper-socket",
  3397. "Socket Path for comminucating with the Virtual MSR helper daemon");
  3398. kvm_arch_accel_class_init(oc);
  3399. }
  3400. static const TypeInfo kvm_accel_type = {
  3401. .name = TYPE_KVM_ACCEL,
  3402. .parent = TYPE_ACCEL,
  3403. .instance_init = kvm_accel_instance_init,
  3404. .class_init = kvm_accel_class_init,
  3405. .instance_size = sizeof(KVMState),
  3406. };
  3407. static void kvm_type_init(void)
  3408. {
  3409. type_register_static(&kvm_accel_type);
  3410. }
  3411. type_init(kvm_type_init);
  3412. typedef struct StatsArgs {
  3413. union StatsResultsType {
  3414. StatsResultList **stats;
  3415. StatsSchemaList **schema;
  3416. } result;
  3417. strList *names;
  3418. Error **errp;
  3419. } StatsArgs;
  3420. static StatsList *add_kvmstat_entry(struct kvm_stats_desc *pdesc,
  3421. uint64_t *stats_data,
  3422. StatsList *stats_list,
  3423. Error **errp)
  3424. {
  3425. Stats *stats;
  3426. uint64List *val_list = NULL;
  3427. /* Only add stats that we understand. */
  3428. switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
  3429. case KVM_STATS_TYPE_CUMULATIVE:
  3430. case KVM_STATS_TYPE_INSTANT:
  3431. case KVM_STATS_TYPE_PEAK:
  3432. case KVM_STATS_TYPE_LINEAR_HIST:
  3433. case KVM_STATS_TYPE_LOG_HIST:
  3434. break;
  3435. default:
  3436. return stats_list;
  3437. }
  3438. switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
  3439. case KVM_STATS_UNIT_NONE:
  3440. case KVM_STATS_UNIT_BYTES:
  3441. case KVM_STATS_UNIT_CYCLES:
  3442. case KVM_STATS_UNIT_SECONDS:
  3443. case KVM_STATS_UNIT_BOOLEAN:
  3444. break;
  3445. default:
  3446. return stats_list;
  3447. }
  3448. switch (pdesc->flags & KVM_STATS_BASE_MASK) {
  3449. case KVM_STATS_BASE_POW10:
  3450. case KVM_STATS_BASE_POW2:
  3451. break;
  3452. default:
  3453. return stats_list;
  3454. }
  3455. /* Alloc and populate data list */
  3456. stats = g_new0(Stats, 1);
  3457. stats->name = g_strdup(pdesc->name);
  3458. stats->value = g_new0(StatsValue, 1);
  3459. if ((pdesc->flags & KVM_STATS_UNIT_MASK) == KVM_STATS_UNIT_BOOLEAN) {
  3460. stats->value->u.boolean = *stats_data;
  3461. stats->value->type = QTYPE_QBOOL;
  3462. } else if (pdesc->size == 1) {
  3463. stats->value->u.scalar = *stats_data;
  3464. stats->value->type = QTYPE_QNUM;
  3465. } else {
  3466. int i;
  3467. for (i = 0; i < pdesc->size; i++) {
  3468. QAPI_LIST_PREPEND(val_list, stats_data[i]);
  3469. }
  3470. stats->value->u.list = val_list;
  3471. stats->value->type = QTYPE_QLIST;
  3472. }
  3473. QAPI_LIST_PREPEND(stats_list, stats);
  3474. return stats_list;
  3475. }
  3476. static StatsSchemaValueList *add_kvmschema_entry(struct kvm_stats_desc *pdesc,
  3477. StatsSchemaValueList *list,
  3478. Error **errp)
  3479. {
  3480. StatsSchemaValueList *schema_entry = g_new0(StatsSchemaValueList, 1);
  3481. schema_entry->value = g_new0(StatsSchemaValue, 1);
  3482. switch (pdesc->flags & KVM_STATS_TYPE_MASK) {
  3483. case KVM_STATS_TYPE_CUMULATIVE:
  3484. schema_entry->value->type = STATS_TYPE_CUMULATIVE;
  3485. break;
  3486. case KVM_STATS_TYPE_INSTANT:
  3487. schema_entry->value->type = STATS_TYPE_INSTANT;
  3488. break;
  3489. case KVM_STATS_TYPE_PEAK:
  3490. schema_entry->value->type = STATS_TYPE_PEAK;
  3491. break;
  3492. case KVM_STATS_TYPE_LINEAR_HIST:
  3493. schema_entry->value->type = STATS_TYPE_LINEAR_HISTOGRAM;
  3494. schema_entry->value->bucket_size = pdesc->bucket_size;
  3495. schema_entry->value->has_bucket_size = true;
  3496. break;
  3497. case KVM_STATS_TYPE_LOG_HIST:
  3498. schema_entry->value->type = STATS_TYPE_LOG2_HISTOGRAM;
  3499. break;
  3500. default:
  3501. goto exit;
  3502. }
  3503. switch (pdesc->flags & KVM_STATS_UNIT_MASK) {
  3504. case KVM_STATS_UNIT_NONE:
  3505. break;
  3506. case KVM_STATS_UNIT_BOOLEAN:
  3507. schema_entry->value->has_unit = true;
  3508. schema_entry->value->unit = STATS_UNIT_BOOLEAN;
  3509. break;
  3510. case KVM_STATS_UNIT_BYTES:
  3511. schema_entry->value->has_unit = true;
  3512. schema_entry->value->unit = STATS_UNIT_BYTES;
  3513. break;
  3514. case KVM_STATS_UNIT_CYCLES:
  3515. schema_entry->value->has_unit = true;
  3516. schema_entry->value->unit = STATS_UNIT_CYCLES;
  3517. break;
  3518. case KVM_STATS_UNIT_SECONDS:
  3519. schema_entry->value->has_unit = true;
  3520. schema_entry->value->unit = STATS_UNIT_SECONDS;
  3521. break;
  3522. default:
  3523. goto exit;
  3524. }
  3525. schema_entry->value->exponent = pdesc->exponent;
  3526. if (pdesc->exponent) {
  3527. switch (pdesc->flags & KVM_STATS_BASE_MASK) {
  3528. case KVM_STATS_BASE_POW10:
  3529. schema_entry->value->has_base = true;
  3530. schema_entry->value->base = 10;
  3531. break;
  3532. case KVM_STATS_BASE_POW2:
  3533. schema_entry->value->has_base = true;
  3534. schema_entry->value->base = 2;
  3535. break;
  3536. default:
  3537. goto exit;
  3538. }
  3539. }
  3540. schema_entry->value->name = g_strdup(pdesc->name);
  3541. schema_entry->next = list;
  3542. return schema_entry;
  3543. exit:
  3544. g_free(schema_entry->value);
  3545. g_free(schema_entry);
  3546. return list;
  3547. }
  3548. /* Cached stats descriptors */
  3549. typedef struct StatsDescriptors {
  3550. const char *ident; /* cache key, currently the StatsTarget */
  3551. struct kvm_stats_desc *kvm_stats_desc;
  3552. struct kvm_stats_header kvm_stats_header;
  3553. QTAILQ_ENTRY(StatsDescriptors) next;
  3554. } StatsDescriptors;
  3555. static QTAILQ_HEAD(, StatsDescriptors) stats_descriptors =
  3556. QTAILQ_HEAD_INITIALIZER(stats_descriptors);
  3557. /*
  3558. * Return the descriptors for 'target', that either have already been read
  3559. * or are retrieved from 'stats_fd'.
  3560. */
  3561. static StatsDescriptors *find_stats_descriptors(StatsTarget target, int stats_fd,
  3562. Error **errp)
  3563. {
  3564. StatsDescriptors *descriptors;
  3565. const char *ident;
  3566. struct kvm_stats_desc *kvm_stats_desc;
  3567. struct kvm_stats_header *kvm_stats_header;
  3568. size_t size_desc;
  3569. ssize_t ret;
  3570. ident = StatsTarget_str(target);
  3571. QTAILQ_FOREACH(descriptors, &stats_descriptors, next) {
  3572. if (g_str_equal(descriptors->ident, ident)) {
  3573. return descriptors;
  3574. }
  3575. }
  3576. descriptors = g_new0(StatsDescriptors, 1);
  3577. /* Read stats header */
  3578. kvm_stats_header = &descriptors->kvm_stats_header;
  3579. ret = pread(stats_fd, kvm_stats_header, sizeof(*kvm_stats_header), 0);
  3580. if (ret != sizeof(*kvm_stats_header)) {
  3581. error_setg(errp, "KVM stats: failed to read stats header: "
  3582. "expected %zu actual %zu",
  3583. sizeof(*kvm_stats_header), ret);
  3584. g_free(descriptors);
  3585. return NULL;
  3586. }
  3587. size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
  3588. /* Read stats descriptors */
  3589. kvm_stats_desc = g_malloc0_n(kvm_stats_header->num_desc, size_desc);
  3590. ret = pread(stats_fd, kvm_stats_desc,
  3591. size_desc * kvm_stats_header->num_desc,
  3592. kvm_stats_header->desc_offset);
  3593. if (ret != size_desc * kvm_stats_header->num_desc) {
  3594. error_setg(errp, "KVM stats: failed to read stats descriptors: "
  3595. "expected %zu actual %zu",
  3596. size_desc * kvm_stats_header->num_desc, ret);
  3597. g_free(descriptors);
  3598. g_free(kvm_stats_desc);
  3599. return NULL;
  3600. }
  3601. descriptors->kvm_stats_desc = kvm_stats_desc;
  3602. descriptors->ident = ident;
  3603. QTAILQ_INSERT_TAIL(&stats_descriptors, descriptors, next);
  3604. return descriptors;
  3605. }
  3606. static void query_stats(StatsResultList **result, StatsTarget target,
  3607. strList *names, int stats_fd, CPUState *cpu,
  3608. Error **errp)
  3609. {
  3610. struct kvm_stats_desc *kvm_stats_desc;
  3611. struct kvm_stats_header *kvm_stats_header;
  3612. StatsDescriptors *descriptors;
  3613. g_autofree uint64_t *stats_data = NULL;
  3614. struct kvm_stats_desc *pdesc;
  3615. StatsList *stats_list = NULL;
  3616. size_t size_desc, size_data = 0;
  3617. ssize_t ret;
  3618. int i;
  3619. descriptors = find_stats_descriptors(target, stats_fd, errp);
  3620. if (!descriptors) {
  3621. return;
  3622. }
  3623. kvm_stats_header = &descriptors->kvm_stats_header;
  3624. kvm_stats_desc = descriptors->kvm_stats_desc;
  3625. size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
  3626. /* Tally the total data size; read schema data */
  3627. for (i = 0; i < kvm_stats_header->num_desc; ++i) {
  3628. pdesc = (void *)kvm_stats_desc + i * size_desc;
  3629. size_data += pdesc->size * sizeof(*stats_data);
  3630. }
  3631. stats_data = g_malloc0(size_data);
  3632. ret = pread(stats_fd, stats_data, size_data, kvm_stats_header->data_offset);
  3633. if (ret != size_data) {
  3634. error_setg(errp, "KVM stats: failed to read data: "
  3635. "expected %zu actual %zu", size_data, ret);
  3636. return;
  3637. }
  3638. for (i = 0; i < kvm_stats_header->num_desc; ++i) {
  3639. uint64_t *stats;
  3640. pdesc = (void *)kvm_stats_desc + i * size_desc;
  3641. /* Add entry to the list */
  3642. stats = (void *)stats_data + pdesc->offset;
  3643. if (!apply_str_list_filter(pdesc->name, names)) {
  3644. continue;
  3645. }
  3646. stats_list = add_kvmstat_entry(pdesc, stats, stats_list, errp);
  3647. }
  3648. if (!stats_list) {
  3649. return;
  3650. }
  3651. switch (target) {
  3652. case STATS_TARGET_VM:
  3653. add_stats_entry(result, STATS_PROVIDER_KVM, NULL, stats_list);
  3654. break;
  3655. case STATS_TARGET_VCPU:
  3656. add_stats_entry(result, STATS_PROVIDER_KVM,
  3657. cpu->parent_obj.canonical_path,
  3658. stats_list);
  3659. break;
  3660. default:
  3661. g_assert_not_reached();
  3662. }
  3663. }
  3664. static void query_stats_schema(StatsSchemaList **result, StatsTarget target,
  3665. int stats_fd, Error **errp)
  3666. {
  3667. struct kvm_stats_desc *kvm_stats_desc;
  3668. struct kvm_stats_header *kvm_stats_header;
  3669. StatsDescriptors *descriptors;
  3670. struct kvm_stats_desc *pdesc;
  3671. StatsSchemaValueList *stats_list = NULL;
  3672. size_t size_desc;
  3673. int i;
  3674. descriptors = find_stats_descriptors(target, stats_fd, errp);
  3675. if (!descriptors) {
  3676. return;
  3677. }
  3678. kvm_stats_header = &descriptors->kvm_stats_header;
  3679. kvm_stats_desc = descriptors->kvm_stats_desc;
  3680. size_desc = sizeof(*kvm_stats_desc) + kvm_stats_header->name_size;
  3681. /* Tally the total data size; read schema data */
  3682. for (i = 0; i < kvm_stats_header->num_desc; ++i) {
  3683. pdesc = (void *)kvm_stats_desc + i * size_desc;
  3684. stats_list = add_kvmschema_entry(pdesc, stats_list, errp);
  3685. }
  3686. add_stats_schema(result, STATS_PROVIDER_KVM, target, stats_list);
  3687. }
  3688. static void query_stats_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
  3689. {
  3690. int stats_fd = cpu->kvm_vcpu_stats_fd;
  3691. Error *local_err = NULL;
  3692. if (stats_fd == -1) {
  3693. error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
  3694. error_propagate(kvm_stats_args->errp, local_err);
  3695. return;
  3696. }
  3697. query_stats(kvm_stats_args->result.stats, STATS_TARGET_VCPU,
  3698. kvm_stats_args->names, stats_fd, cpu,
  3699. kvm_stats_args->errp);
  3700. }
  3701. static void query_stats_schema_vcpu(CPUState *cpu, StatsArgs *kvm_stats_args)
  3702. {
  3703. int stats_fd = cpu->kvm_vcpu_stats_fd;
  3704. Error *local_err = NULL;
  3705. if (stats_fd == -1) {
  3706. error_setg_errno(&local_err, errno, "KVM stats: ioctl failed");
  3707. error_propagate(kvm_stats_args->errp, local_err);
  3708. return;
  3709. }
  3710. query_stats_schema(kvm_stats_args->result.schema, STATS_TARGET_VCPU, stats_fd,
  3711. kvm_stats_args->errp);
  3712. }
  3713. static void query_stats_cb(StatsResultList **result, StatsTarget target,
  3714. strList *names, strList *targets, Error **errp)
  3715. {
  3716. KVMState *s = kvm_state;
  3717. CPUState *cpu;
  3718. int stats_fd;
  3719. switch (target) {
  3720. case STATS_TARGET_VM:
  3721. {
  3722. stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
  3723. if (stats_fd == -1) {
  3724. error_setg_errno(errp, errno, "KVM stats: ioctl failed");
  3725. return;
  3726. }
  3727. query_stats(result, target, names, stats_fd, NULL, errp);
  3728. close(stats_fd);
  3729. break;
  3730. }
  3731. case STATS_TARGET_VCPU:
  3732. {
  3733. StatsArgs stats_args;
  3734. stats_args.result.stats = result;
  3735. stats_args.names = names;
  3736. stats_args.errp = errp;
  3737. CPU_FOREACH(cpu) {
  3738. if (!apply_str_list_filter(cpu->parent_obj.canonical_path, targets)) {
  3739. continue;
  3740. }
  3741. query_stats_vcpu(cpu, &stats_args);
  3742. }
  3743. break;
  3744. }
  3745. default:
  3746. break;
  3747. }
  3748. }
  3749. void query_stats_schemas_cb(StatsSchemaList **result, Error **errp)
  3750. {
  3751. StatsArgs stats_args;
  3752. KVMState *s = kvm_state;
  3753. int stats_fd;
  3754. stats_fd = kvm_vm_ioctl(s, KVM_GET_STATS_FD, NULL);
  3755. if (stats_fd == -1) {
  3756. error_setg_errno(errp, errno, "KVM stats: ioctl failed");
  3757. return;
  3758. }
  3759. query_stats_schema(result, STATS_TARGET_VM, stats_fd, errp);
  3760. close(stats_fd);
  3761. if (first_cpu) {
  3762. stats_args.result.schema = result;
  3763. stats_args.errp = errp;
  3764. query_stats_schema_vcpu(first_cpu, &stats_args);
  3765. }
  3766. }
  3767. void kvm_mark_guest_state_protected(void)
  3768. {
  3769. kvm_state->guest_state_protected = true;
  3770. }
  3771. int kvm_create_guest_memfd(uint64_t size, uint64_t flags, Error **errp)
  3772. {
  3773. int fd;
  3774. struct kvm_create_guest_memfd guest_memfd = {
  3775. .size = size,
  3776. .flags = flags,
  3777. };
  3778. if (!kvm_guest_memfd_supported) {
  3779. error_setg(errp, "KVM does not support guest_memfd");
  3780. return -1;
  3781. }
  3782. fd = kvm_vm_ioctl(kvm_state, KVM_CREATE_GUEST_MEMFD, &guest_memfd);
  3783. if (fd < 0) {
  3784. error_setg_errno(errp, errno, "Error creating KVM guest_memfd");
  3785. return -1;
  3786. }
  3787. return fd;
  3788. }