kvm-all.c 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  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 <linux/kvm.h>
  18. #include "qemu-common.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 "hw/hw.h"
  24. #include "hw/pci/msi.h"
  25. #include "hw/pci/msix.h"
  26. #include "hw/s390x/adapter.h"
  27. #include "exec/gdbstub.h"
  28. #include "sysemu/kvm_int.h"
  29. #include "qemu/bswap.h"
  30. #include "exec/memory.h"
  31. #include "exec/ram_addr.h"
  32. #include "exec/address-spaces.h"
  33. #include "qemu/event_notifier.h"
  34. #include "trace-root.h"
  35. #include "hw/irq.h"
  36. #include "hw/boards.h"
  37. /* This check must be after config-host.h is included */
  38. #ifdef CONFIG_EVENTFD
  39. #include <sys/eventfd.h>
  40. #endif
  41. /* KVM uses PAGE_SIZE in its definition of KVM_COALESCED_MMIO_MAX. We
  42. * need to use the real host PAGE_SIZE, as that's what KVM will use.
  43. */
  44. #define PAGE_SIZE getpagesize()
  45. //#define DEBUG_KVM
  46. #ifdef DEBUG_KVM
  47. #define DPRINTF(fmt, ...) \
  48. do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0)
  49. #else
  50. #define DPRINTF(fmt, ...) \
  51. do { } while (0)
  52. #endif
  53. #define KVM_MSI_HASHTAB_SIZE 256
  54. struct KVMParkedVcpu {
  55. unsigned long vcpu_id;
  56. int kvm_fd;
  57. QLIST_ENTRY(KVMParkedVcpu) node;
  58. };
  59. struct KVMState
  60. {
  61. AccelState parent_obj;
  62. int nr_slots;
  63. int fd;
  64. int vmfd;
  65. int coalesced_mmio;
  66. struct kvm_coalesced_mmio_ring *coalesced_mmio_ring;
  67. bool coalesced_flush_in_progress;
  68. int broken_set_mem_region;
  69. int vcpu_events;
  70. int robust_singlestep;
  71. int debugregs;
  72. #ifdef KVM_CAP_SET_GUEST_DEBUG
  73. struct kvm_sw_breakpoint_head kvm_sw_breakpoints;
  74. #endif
  75. int many_ioeventfds;
  76. int intx_set_mask;
  77. /* The man page (and posix) say ioctl numbers are signed int, but
  78. * they're not. Linux, glibc and *BSD all treat ioctl numbers as
  79. * unsigned, and treating them as signed here can break things */
  80. unsigned irq_set_ioctl;
  81. unsigned int sigmask_len;
  82. GHashTable *gsimap;
  83. #ifdef KVM_CAP_IRQ_ROUTING
  84. struct kvm_irq_routing *irq_routes;
  85. int nr_allocated_irq_routes;
  86. unsigned long *used_gsi_bitmap;
  87. unsigned int gsi_count;
  88. QTAILQ_HEAD(msi_hashtab, KVMMSIRoute) msi_hashtab[KVM_MSI_HASHTAB_SIZE];
  89. #endif
  90. KVMMemoryListener memory_listener;
  91. QLIST_HEAD(, KVMParkedVcpu) kvm_parked_vcpus;
  92. };
  93. KVMState *kvm_state;
  94. bool kvm_kernel_irqchip;
  95. bool kvm_split_irqchip;
  96. bool kvm_async_interrupts_allowed;
  97. bool kvm_halt_in_kernel_allowed;
  98. bool kvm_eventfds_allowed;
  99. bool kvm_irqfds_allowed;
  100. bool kvm_resamplefds_allowed;
  101. bool kvm_msi_via_irqfd_allowed;
  102. bool kvm_gsi_routing_allowed;
  103. bool kvm_gsi_direct_mapping;
  104. bool kvm_allowed;
  105. bool kvm_readonly_mem_allowed;
  106. bool kvm_vm_attributes_allowed;
  107. bool kvm_direct_msi_allowed;
  108. bool kvm_ioeventfd_any_length_allowed;
  109. bool kvm_msi_use_devid;
  110. static const KVMCapabilityInfo kvm_required_capabilites[] = {
  111. KVM_CAP_INFO(USER_MEMORY),
  112. KVM_CAP_INFO(DESTROY_MEMORY_REGION_WORKS),
  113. KVM_CAP_LAST_INFO
  114. };
  115. int kvm_get_max_memslots(void)
  116. {
  117. KVMState *s = KVM_STATE(current_machine->accelerator);
  118. return s->nr_slots;
  119. }
  120. static KVMSlot *kvm_get_free_slot(KVMMemoryListener *kml)
  121. {
  122. KVMState *s = kvm_state;
  123. int i;
  124. for (i = 0; i < s->nr_slots; i++) {
  125. if (kml->slots[i].memory_size == 0) {
  126. return &kml->slots[i];
  127. }
  128. }
  129. return NULL;
  130. }
  131. bool kvm_has_free_slot(MachineState *ms)
  132. {
  133. KVMState *s = KVM_STATE(ms->accelerator);
  134. return kvm_get_free_slot(&s->memory_listener);
  135. }
  136. static KVMSlot *kvm_alloc_slot(KVMMemoryListener *kml)
  137. {
  138. KVMSlot *slot = kvm_get_free_slot(kml);
  139. if (slot) {
  140. return slot;
  141. }
  142. fprintf(stderr, "%s: no free slot available\n", __func__);
  143. abort();
  144. }
  145. static KVMSlot *kvm_lookup_matching_slot(KVMMemoryListener *kml,
  146. hwaddr start_addr,
  147. hwaddr end_addr)
  148. {
  149. KVMState *s = kvm_state;
  150. int i;
  151. for (i = 0; i < s->nr_slots; i++) {
  152. KVMSlot *mem = &kml->slots[i];
  153. if (start_addr == mem->start_addr &&
  154. end_addr == mem->start_addr + mem->memory_size) {
  155. return mem;
  156. }
  157. }
  158. return NULL;
  159. }
  160. /*
  161. * Find overlapping slot with lowest start address
  162. */
  163. static KVMSlot *kvm_lookup_overlapping_slot(KVMMemoryListener *kml,
  164. hwaddr start_addr,
  165. hwaddr end_addr)
  166. {
  167. KVMState *s = kvm_state;
  168. KVMSlot *found = NULL;
  169. int i;
  170. for (i = 0; i < s->nr_slots; i++) {
  171. KVMSlot *mem = &kml->slots[i];
  172. if (mem->memory_size == 0 ||
  173. (found && found->start_addr < mem->start_addr)) {
  174. continue;
  175. }
  176. if (end_addr > mem->start_addr &&
  177. start_addr < mem->start_addr + mem->memory_size) {
  178. found = mem;
  179. }
  180. }
  181. return found;
  182. }
  183. int kvm_physical_memory_addr_from_host(KVMState *s, void *ram,
  184. hwaddr *phys_addr)
  185. {
  186. KVMMemoryListener *kml = &s->memory_listener;
  187. int i;
  188. for (i = 0; i < s->nr_slots; i++) {
  189. KVMSlot *mem = &kml->slots[i];
  190. if (ram >= mem->ram && ram < mem->ram + mem->memory_size) {
  191. *phys_addr = mem->start_addr + (ram - mem->ram);
  192. return 1;
  193. }
  194. }
  195. return 0;
  196. }
  197. static int kvm_set_user_memory_region(KVMMemoryListener *kml, KVMSlot *slot)
  198. {
  199. KVMState *s = kvm_state;
  200. struct kvm_userspace_memory_region mem;
  201. mem.slot = slot->slot | (kml->as_id << 16);
  202. mem.guest_phys_addr = slot->start_addr;
  203. mem.userspace_addr = (unsigned long)slot->ram;
  204. mem.flags = slot->flags;
  205. if (slot->memory_size && mem.flags & KVM_MEM_READONLY) {
  206. /* Set the slot size to 0 before setting the slot to the desired
  207. * value. This is needed based on KVM commit 75d61fbc. */
  208. mem.memory_size = 0;
  209. kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
  210. }
  211. mem.memory_size = slot->memory_size;
  212. return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);
  213. }
  214. int kvm_destroy_vcpu(CPUState *cpu)
  215. {
  216. KVMState *s = kvm_state;
  217. long mmap_size;
  218. struct KVMParkedVcpu *vcpu = NULL;
  219. int ret = 0;
  220. DPRINTF("kvm_destroy_vcpu\n");
  221. mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
  222. if (mmap_size < 0) {
  223. ret = mmap_size;
  224. DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
  225. goto err;
  226. }
  227. ret = munmap(cpu->kvm_run, mmap_size);
  228. if (ret < 0) {
  229. goto err;
  230. }
  231. vcpu = g_malloc0(sizeof(*vcpu));
  232. vcpu->vcpu_id = kvm_arch_vcpu_id(cpu);
  233. vcpu->kvm_fd = cpu->kvm_fd;
  234. QLIST_INSERT_HEAD(&kvm_state->kvm_parked_vcpus, vcpu, node);
  235. err:
  236. return ret;
  237. }
  238. static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
  239. {
  240. struct KVMParkedVcpu *cpu;
  241. QLIST_FOREACH(cpu, &s->kvm_parked_vcpus, node) {
  242. if (cpu->vcpu_id == vcpu_id) {
  243. int kvm_fd;
  244. QLIST_REMOVE(cpu, node);
  245. kvm_fd = cpu->kvm_fd;
  246. g_free(cpu);
  247. return kvm_fd;
  248. }
  249. }
  250. return kvm_vm_ioctl(s, KVM_CREATE_VCPU, (void *)vcpu_id);
  251. }
  252. int kvm_init_vcpu(CPUState *cpu)
  253. {
  254. KVMState *s = kvm_state;
  255. long mmap_size;
  256. int ret;
  257. DPRINTF("kvm_init_vcpu\n");
  258. ret = kvm_get_vcpu(s, kvm_arch_vcpu_id(cpu));
  259. if (ret < 0) {
  260. DPRINTF("kvm_create_vcpu failed\n");
  261. goto err;
  262. }
  263. cpu->kvm_fd = ret;
  264. cpu->kvm_state = s;
  265. cpu->kvm_vcpu_dirty = true;
  266. mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);
  267. if (mmap_size < 0) {
  268. ret = mmap_size;
  269. DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");
  270. goto err;
  271. }
  272. cpu->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,
  273. cpu->kvm_fd, 0);
  274. if (cpu->kvm_run == MAP_FAILED) {
  275. ret = -errno;
  276. DPRINTF("mmap'ing vcpu state failed\n");
  277. goto err;
  278. }
  279. if (s->coalesced_mmio && !s->coalesced_mmio_ring) {
  280. s->coalesced_mmio_ring =
  281. (void *)cpu->kvm_run + s->coalesced_mmio * PAGE_SIZE;
  282. }
  283. ret = kvm_arch_init_vcpu(cpu);
  284. err:
  285. return ret;
  286. }
  287. /*
  288. * dirty pages logging control
  289. */
  290. static int kvm_mem_flags(MemoryRegion *mr)
  291. {
  292. bool readonly = mr->readonly || memory_region_is_romd(mr);
  293. int flags = 0;
  294. if (memory_region_get_dirty_log_mask(mr) != 0) {
  295. flags |= KVM_MEM_LOG_DIRTY_PAGES;
  296. }
  297. if (readonly && kvm_readonly_mem_allowed) {
  298. flags |= KVM_MEM_READONLY;
  299. }
  300. return flags;
  301. }
  302. static int kvm_slot_update_flags(KVMMemoryListener *kml, KVMSlot *mem,
  303. MemoryRegion *mr)
  304. {
  305. int old_flags;
  306. old_flags = mem->flags;
  307. mem->flags = kvm_mem_flags(mr);
  308. /* If nothing changed effectively, no need to issue ioctl */
  309. if (mem->flags == old_flags) {
  310. return 0;
  311. }
  312. return kvm_set_user_memory_region(kml, mem);
  313. }
  314. static int kvm_section_update_flags(KVMMemoryListener *kml,
  315. MemoryRegionSection *section)
  316. {
  317. hwaddr phys_addr = section->offset_within_address_space;
  318. ram_addr_t size = int128_get64(section->size);
  319. KVMSlot *mem = kvm_lookup_matching_slot(kml, phys_addr, phys_addr + size);
  320. if (mem == NULL) {
  321. return 0;
  322. } else {
  323. return kvm_slot_update_flags(kml, mem, section->mr);
  324. }
  325. }
  326. static void kvm_log_start(MemoryListener *listener,
  327. MemoryRegionSection *section,
  328. int old, int new)
  329. {
  330. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  331. int r;
  332. if (old != 0) {
  333. return;
  334. }
  335. r = kvm_section_update_flags(kml, section);
  336. if (r < 0) {
  337. abort();
  338. }
  339. }
  340. static void kvm_log_stop(MemoryListener *listener,
  341. MemoryRegionSection *section,
  342. int old, int new)
  343. {
  344. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  345. int r;
  346. if (new != 0) {
  347. return;
  348. }
  349. r = kvm_section_update_flags(kml, section);
  350. if (r < 0) {
  351. abort();
  352. }
  353. }
  354. /* get kvm's dirty pages bitmap and update qemu's */
  355. static int kvm_get_dirty_pages_log_range(MemoryRegionSection *section,
  356. unsigned long *bitmap)
  357. {
  358. ram_addr_t start = section->offset_within_region +
  359. memory_region_get_ram_addr(section->mr);
  360. ram_addr_t pages = int128_get64(section->size) / getpagesize();
  361. cpu_physical_memory_set_dirty_lebitmap(bitmap, start, pages);
  362. return 0;
  363. }
  364. #define ALIGN(x, y) (((x)+(y)-1) & ~((y)-1))
  365. /**
  366. * kvm_physical_sync_dirty_bitmap - Grab dirty bitmap from kernel space
  367. * This function updates qemu's dirty bitmap using
  368. * memory_region_set_dirty(). This means all bits are set
  369. * to dirty.
  370. *
  371. * @start_add: start of logged region.
  372. * @end_addr: end of logged region.
  373. */
  374. static int kvm_physical_sync_dirty_bitmap(KVMMemoryListener *kml,
  375. MemoryRegionSection *section)
  376. {
  377. KVMState *s = kvm_state;
  378. unsigned long size, allocated_size = 0;
  379. struct kvm_dirty_log d = {};
  380. KVMSlot *mem;
  381. int ret = 0;
  382. hwaddr start_addr = section->offset_within_address_space;
  383. hwaddr end_addr = start_addr + int128_get64(section->size);
  384. d.dirty_bitmap = NULL;
  385. while (start_addr < end_addr) {
  386. mem = kvm_lookup_overlapping_slot(kml, start_addr, end_addr);
  387. if (mem == NULL) {
  388. break;
  389. }
  390. /* XXX bad kernel interface alert
  391. * For dirty bitmap, kernel allocates array of size aligned to
  392. * bits-per-long. But for case when the kernel is 64bits and
  393. * the userspace is 32bits, userspace can't align to the same
  394. * bits-per-long, since sizeof(long) is different between kernel
  395. * and user space. This way, userspace will provide buffer which
  396. * may be 4 bytes less than the kernel will use, resulting in
  397. * userspace memory corruption (which is not detectable by valgrind
  398. * too, in most cases).
  399. * So for now, let's align to 64 instead of HOST_LONG_BITS here, in
  400. * a hope that sizeof(long) won't become >8 any time soon.
  401. */
  402. size = ALIGN(((mem->memory_size) >> TARGET_PAGE_BITS),
  403. /*HOST_LONG_BITS*/ 64) / 8;
  404. if (!d.dirty_bitmap) {
  405. d.dirty_bitmap = g_malloc(size);
  406. } else if (size > allocated_size) {
  407. d.dirty_bitmap = g_realloc(d.dirty_bitmap, size);
  408. }
  409. allocated_size = size;
  410. memset(d.dirty_bitmap, 0, allocated_size);
  411. d.slot = mem->slot | (kml->as_id << 16);
  412. if (kvm_vm_ioctl(s, KVM_GET_DIRTY_LOG, &d) == -1) {
  413. DPRINTF("ioctl failed %d\n", errno);
  414. ret = -1;
  415. break;
  416. }
  417. kvm_get_dirty_pages_log_range(section, d.dirty_bitmap);
  418. start_addr = mem->start_addr + mem->memory_size;
  419. }
  420. g_free(d.dirty_bitmap);
  421. return ret;
  422. }
  423. static void kvm_coalesce_mmio_region(MemoryListener *listener,
  424. MemoryRegionSection *secion,
  425. hwaddr start, hwaddr size)
  426. {
  427. KVMState *s = kvm_state;
  428. if (s->coalesced_mmio) {
  429. struct kvm_coalesced_mmio_zone zone;
  430. zone.addr = start;
  431. zone.size = size;
  432. zone.pad = 0;
  433. (void)kvm_vm_ioctl(s, KVM_REGISTER_COALESCED_MMIO, &zone);
  434. }
  435. }
  436. static void kvm_uncoalesce_mmio_region(MemoryListener *listener,
  437. MemoryRegionSection *secion,
  438. hwaddr start, hwaddr size)
  439. {
  440. KVMState *s = kvm_state;
  441. if (s->coalesced_mmio) {
  442. struct kvm_coalesced_mmio_zone zone;
  443. zone.addr = start;
  444. zone.size = size;
  445. zone.pad = 0;
  446. (void)kvm_vm_ioctl(s, KVM_UNREGISTER_COALESCED_MMIO, &zone);
  447. }
  448. }
  449. int kvm_check_extension(KVMState *s, unsigned int extension)
  450. {
  451. int ret;
  452. ret = kvm_ioctl(s, KVM_CHECK_EXTENSION, extension);
  453. if (ret < 0) {
  454. ret = 0;
  455. }
  456. return ret;
  457. }
  458. int kvm_vm_check_extension(KVMState *s, unsigned int extension)
  459. {
  460. int ret;
  461. ret = kvm_vm_ioctl(s, KVM_CHECK_EXTENSION, extension);
  462. if (ret < 0) {
  463. /* VM wide version not implemented, use global one instead */
  464. ret = kvm_check_extension(s, extension);
  465. }
  466. return ret;
  467. }
  468. static uint32_t adjust_ioeventfd_endianness(uint32_t val, uint32_t size)
  469. {
  470. #if defined(HOST_WORDS_BIGENDIAN) != defined(TARGET_WORDS_BIGENDIAN)
  471. /* The kernel expects ioeventfd values in HOST_WORDS_BIGENDIAN
  472. * endianness, but the memory core hands them in target endianness.
  473. * For example, PPC is always treated as big-endian even if running
  474. * on KVM and on PPC64LE. Correct here.
  475. */
  476. switch (size) {
  477. case 2:
  478. val = bswap16(val);
  479. break;
  480. case 4:
  481. val = bswap32(val);
  482. break;
  483. }
  484. #endif
  485. return val;
  486. }
  487. static int kvm_set_ioeventfd_mmio(int fd, hwaddr addr, uint32_t val,
  488. bool assign, uint32_t size, bool datamatch)
  489. {
  490. int ret;
  491. struct kvm_ioeventfd iofd = {
  492. .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
  493. .addr = addr,
  494. .len = size,
  495. .flags = 0,
  496. .fd = fd,
  497. };
  498. if (!kvm_enabled()) {
  499. return -ENOSYS;
  500. }
  501. if (datamatch) {
  502. iofd.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
  503. }
  504. if (!assign) {
  505. iofd.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
  506. }
  507. ret = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &iofd);
  508. if (ret < 0) {
  509. return -errno;
  510. }
  511. return 0;
  512. }
  513. static int kvm_set_ioeventfd_pio(int fd, uint16_t addr, uint16_t val,
  514. bool assign, uint32_t size, bool datamatch)
  515. {
  516. struct kvm_ioeventfd kick = {
  517. .datamatch = datamatch ? adjust_ioeventfd_endianness(val, size) : 0,
  518. .addr = addr,
  519. .flags = KVM_IOEVENTFD_FLAG_PIO,
  520. .len = size,
  521. .fd = fd,
  522. };
  523. int r;
  524. if (!kvm_enabled()) {
  525. return -ENOSYS;
  526. }
  527. if (datamatch) {
  528. kick.flags |= KVM_IOEVENTFD_FLAG_DATAMATCH;
  529. }
  530. if (!assign) {
  531. kick.flags |= KVM_IOEVENTFD_FLAG_DEASSIGN;
  532. }
  533. r = kvm_vm_ioctl(kvm_state, KVM_IOEVENTFD, &kick);
  534. if (r < 0) {
  535. return r;
  536. }
  537. return 0;
  538. }
  539. static int kvm_check_many_ioeventfds(void)
  540. {
  541. /* Userspace can use ioeventfd for io notification. This requires a host
  542. * that supports eventfd(2) and an I/O thread; since eventfd does not
  543. * support SIGIO it cannot interrupt the vcpu.
  544. *
  545. * Older kernels have a 6 device limit on the KVM io bus. Find out so we
  546. * can avoid creating too many ioeventfds.
  547. */
  548. #if defined(CONFIG_EVENTFD)
  549. int ioeventfds[7];
  550. int i, ret = 0;
  551. for (i = 0; i < ARRAY_SIZE(ioeventfds); i++) {
  552. ioeventfds[i] = eventfd(0, EFD_CLOEXEC);
  553. if (ioeventfds[i] < 0) {
  554. break;
  555. }
  556. ret = kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, true, 2, true);
  557. if (ret < 0) {
  558. close(ioeventfds[i]);
  559. break;
  560. }
  561. }
  562. /* Decide whether many devices are supported or not */
  563. ret = i == ARRAY_SIZE(ioeventfds);
  564. while (i-- > 0) {
  565. kvm_set_ioeventfd_pio(ioeventfds[i], 0, i, false, 2, true);
  566. close(ioeventfds[i]);
  567. }
  568. return ret;
  569. #else
  570. return 0;
  571. #endif
  572. }
  573. static const KVMCapabilityInfo *
  574. kvm_check_extension_list(KVMState *s, const KVMCapabilityInfo *list)
  575. {
  576. while (list->name) {
  577. if (!kvm_check_extension(s, list->value)) {
  578. return list;
  579. }
  580. list++;
  581. }
  582. return NULL;
  583. }
  584. static void kvm_set_phys_mem(KVMMemoryListener *kml,
  585. MemoryRegionSection *section, bool add)
  586. {
  587. KVMState *s = kvm_state;
  588. KVMSlot *mem, old;
  589. int err;
  590. MemoryRegion *mr = section->mr;
  591. bool writeable = !mr->readonly && !mr->rom_device;
  592. hwaddr start_addr = section->offset_within_address_space;
  593. ram_addr_t size = int128_get64(section->size);
  594. void *ram = NULL;
  595. unsigned delta;
  596. /* kvm works in page size chunks, but the function may be called
  597. with sub-page size and unaligned start address. Pad the start
  598. address to next and truncate size to previous page boundary. */
  599. delta = qemu_real_host_page_size - (start_addr & ~qemu_real_host_page_mask);
  600. delta &= ~qemu_real_host_page_mask;
  601. if (delta > size) {
  602. return;
  603. }
  604. start_addr += delta;
  605. size -= delta;
  606. size &= qemu_real_host_page_mask;
  607. if (!size || (start_addr & ~qemu_real_host_page_mask)) {
  608. return;
  609. }
  610. if (!memory_region_is_ram(mr)) {
  611. if (writeable || !kvm_readonly_mem_allowed) {
  612. return;
  613. } else if (!mr->romd_mode) {
  614. /* If the memory device is not in romd_mode, then we actually want
  615. * to remove the kvm memory slot so all accesses will trap. */
  616. add = false;
  617. }
  618. }
  619. ram = memory_region_get_ram_ptr(mr) + section->offset_within_region + delta;
  620. while (1) {
  621. mem = kvm_lookup_overlapping_slot(kml, start_addr, start_addr + size);
  622. if (!mem) {
  623. break;
  624. }
  625. if (add && start_addr >= mem->start_addr &&
  626. (start_addr + size <= mem->start_addr + mem->memory_size) &&
  627. (ram - start_addr == mem->ram - mem->start_addr)) {
  628. /* The new slot fits into the existing one and comes with
  629. * identical parameters - update flags and done. */
  630. kvm_slot_update_flags(kml, mem, mr);
  631. return;
  632. }
  633. old = *mem;
  634. if (mem->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  635. kvm_physical_sync_dirty_bitmap(kml, section);
  636. }
  637. /* unregister the overlapping slot */
  638. mem->memory_size = 0;
  639. err = kvm_set_user_memory_region(kml, mem);
  640. if (err) {
  641. fprintf(stderr, "%s: error unregistering overlapping slot: %s\n",
  642. __func__, strerror(-err));
  643. abort();
  644. }
  645. /* Workaround for older KVM versions: we can't join slots, even not by
  646. * unregistering the previous ones and then registering the larger
  647. * slot. We have to maintain the existing fragmentation. Sigh.
  648. *
  649. * This workaround assumes that the new slot starts at the same
  650. * address as the first existing one. If not or if some overlapping
  651. * slot comes around later, we will fail (not seen in practice so far)
  652. * - and actually require a recent KVM version. */
  653. if (s->broken_set_mem_region &&
  654. old.start_addr == start_addr && old.memory_size < size && add) {
  655. mem = kvm_alloc_slot(kml);
  656. mem->memory_size = old.memory_size;
  657. mem->start_addr = old.start_addr;
  658. mem->ram = old.ram;
  659. mem->flags = kvm_mem_flags(mr);
  660. err = kvm_set_user_memory_region(kml, mem);
  661. if (err) {
  662. fprintf(stderr, "%s: error updating slot: %s\n", __func__,
  663. strerror(-err));
  664. abort();
  665. }
  666. start_addr += old.memory_size;
  667. ram += old.memory_size;
  668. size -= old.memory_size;
  669. continue;
  670. }
  671. /* register prefix slot */
  672. if (old.start_addr < start_addr) {
  673. mem = kvm_alloc_slot(kml);
  674. mem->memory_size = start_addr - old.start_addr;
  675. mem->start_addr = old.start_addr;
  676. mem->ram = old.ram;
  677. mem->flags = kvm_mem_flags(mr);
  678. err = kvm_set_user_memory_region(kml, mem);
  679. if (err) {
  680. fprintf(stderr, "%s: error registering prefix slot: %s\n",
  681. __func__, strerror(-err));
  682. #ifdef TARGET_PPC
  683. fprintf(stderr, "%s: This is probably because your kernel's " \
  684. "PAGE_SIZE is too big. Please try to use 4k " \
  685. "PAGE_SIZE!\n", __func__);
  686. #endif
  687. abort();
  688. }
  689. }
  690. /* register suffix slot */
  691. if (old.start_addr + old.memory_size > start_addr + size) {
  692. ram_addr_t size_delta;
  693. mem = kvm_alloc_slot(kml);
  694. mem->start_addr = start_addr + size;
  695. size_delta = mem->start_addr - old.start_addr;
  696. mem->memory_size = old.memory_size - size_delta;
  697. mem->ram = old.ram + size_delta;
  698. mem->flags = kvm_mem_flags(mr);
  699. err = kvm_set_user_memory_region(kml, mem);
  700. if (err) {
  701. fprintf(stderr, "%s: error registering suffix slot: %s\n",
  702. __func__, strerror(-err));
  703. abort();
  704. }
  705. }
  706. }
  707. /* in case the KVM bug workaround already "consumed" the new slot */
  708. if (!size) {
  709. return;
  710. }
  711. if (!add) {
  712. return;
  713. }
  714. mem = kvm_alloc_slot(kml);
  715. mem->memory_size = size;
  716. mem->start_addr = start_addr;
  717. mem->ram = ram;
  718. mem->flags = kvm_mem_flags(mr);
  719. err = kvm_set_user_memory_region(kml, mem);
  720. if (err) {
  721. fprintf(stderr, "%s: error registering slot: %s\n", __func__,
  722. strerror(-err));
  723. abort();
  724. }
  725. }
  726. static void kvm_region_add(MemoryListener *listener,
  727. MemoryRegionSection *section)
  728. {
  729. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  730. memory_region_ref(section->mr);
  731. kvm_set_phys_mem(kml, section, true);
  732. }
  733. static void kvm_region_del(MemoryListener *listener,
  734. MemoryRegionSection *section)
  735. {
  736. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  737. kvm_set_phys_mem(kml, section, false);
  738. memory_region_unref(section->mr);
  739. }
  740. static void kvm_log_sync(MemoryListener *listener,
  741. MemoryRegionSection *section)
  742. {
  743. KVMMemoryListener *kml = container_of(listener, KVMMemoryListener, listener);
  744. int r;
  745. r = kvm_physical_sync_dirty_bitmap(kml, section);
  746. if (r < 0) {
  747. abort();
  748. }
  749. }
  750. static void kvm_mem_ioeventfd_add(MemoryListener *listener,
  751. MemoryRegionSection *section,
  752. bool match_data, uint64_t data,
  753. EventNotifier *e)
  754. {
  755. int fd = event_notifier_get_fd(e);
  756. int r;
  757. r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
  758. data, true, int128_get64(section->size),
  759. match_data);
  760. if (r < 0) {
  761. fprintf(stderr, "%s: error adding ioeventfd: %s\n",
  762. __func__, strerror(-r));
  763. abort();
  764. }
  765. }
  766. static void kvm_mem_ioeventfd_del(MemoryListener *listener,
  767. MemoryRegionSection *section,
  768. bool match_data, uint64_t data,
  769. EventNotifier *e)
  770. {
  771. int fd = event_notifier_get_fd(e);
  772. int r;
  773. r = kvm_set_ioeventfd_mmio(fd, section->offset_within_address_space,
  774. data, false, int128_get64(section->size),
  775. match_data);
  776. if (r < 0) {
  777. abort();
  778. }
  779. }
  780. static void kvm_io_ioeventfd_add(MemoryListener *listener,
  781. MemoryRegionSection *section,
  782. bool match_data, uint64_t data,
  783. EventNotifier *e)
  784. {
  785. int fd = event_notifier_get_fd(e);
  786. int r;
  787. r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
  788. data, true, int128_get64(section->size),
  789. match_data);
  790. if (r < 0) {
  791. fprintf(stderr, "%s: error adding ioeventfd: %s\n",
  792. __func__, strerror(-r));
  793. abort();
  794. }
  795. }
  796. static void kvm_io_ioeventfd_del(MemoryListener *listener,
  797. MemoryRegionSection *section,
  798. bool match_data, uint64_t data,
  799. EventNotifier *e)
  800. {
  801. int fd = event_notifier_get_fd(e);
  802. int r;
  803. r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,
  804. data, false, int128_get64(section->size),
  805. match_data);
  806. if (r < 0) {
  807. abort();
  808. }
  809. }
  810. void kvm_memory_listener_register(KVMState *s, KVMMemoryListener *kml,
  811. AddressSpace *as, int as_id)
  812. {
  813. int i;
  814. kml->slots = g_malloc0(s->nr_slots * sizeof(KVMSlot));
  815. kml->as_id = as_id;
  816. for (i = 0; i < s->nr_slots; i++) {
  817. kml->slots[i].slot = i;
  818. }
  819. kml->listener.region_add = kvm_region_add;
  820. kml->listener.region_del = kvm_region_del;
  821. kml->listener.log_start = kvm_log_start;
  822. kml->listener.log_stop = kvm_log_stop;
  823. kml->listener.log_sync = kvm_log_sync;
  824. kml->listener.priority = 10;
  825. memory_listener_register(&kml->listener, as);
  826. }
  827. static MemoryListener kvm_io_listener = {
  828. .eventfd_add = kvm_io_ioeventfd_add,
  829. .eventfd_del = kvm_io_ioeventfd_del,
  830. .priority = 10,
  831. };
  832. static void kvm_handle_interrupt(CPUState *cpu, int mask)
  833. {
  834. cpu->interrupt_request |= mask;
  835. if (!qemu_cpu_is_self(cpu)) {
  836. qemu_cpu_kick(cpu);
  837. }
  838. }
  839. int kvm_set_irq(KVMState *s, int irq, int level)
  840. {
  841. struct kvm_irq_level event;
  842. int ret;
  843. assert(kvm_async_interrupts_enabled());
  844. event.level = level;
  845. event.irq = irq;
  846. ret = kvm_vm_ioctl(s, s->irq_set_ioctl, &event);
  847. if (ret < 0) {
  848. perror("kvm_set_irq");
  849. abort();
  850. }
  851. return (s->irq_set_ioctl == KVM_IRQ_LINE) ? 1 : event.status;
  852. }
  853. #ifdef KVM_CAP_IRQ_ROUTING
  854. typedef struct KVMMSIRoute {
  855. struct kvm_irq_routing_entry kroute;
  856. QTAILQ_ENTRY(KVMMSIRoute) entry;
  857. } KVMMSIRoute;
  858. static void set_gsi(KVMState *s, unsigned int gsi)
  859. {
  860. set_bit(gsi, s->used_gsi_bitmap);
  861. }
  862. static void clear_gsi(KVMState *s, unsigned int gsi)
  863. {
  864. clear_bit(gsi, s->used_gsi_bitmap);
  865. }
  866. void kvm_init_irq_routing(KVMState *s)
  867. {
  868. int gsi_count, i;
  869. gsi_count = kvm_check_extension(s, KVM_CAP_IRQ_ROUTING) - 1;
  870. if (gsi_count > 0) {
  871. /* Round up so we can search ints using ffs */
  872. s->used_gsi_bitmap = bitmap_new(gsi_count);
  873. s->gsi_count = gsi_count;
  874. }
  875. s->irq_routes = g_malloc0(sizeof(*s->irq_routes));
  876. s->nr_allocated_irq_routes = 0;
  877. if (!kvm_direct_msi_allowed) {
  878. for (i = 0; i < KVM_MSI_HASHTAB_SIZE; i++) {
  879. QTAILQ_INIT(&s->msi_hashtab[i]);
  880. }
  881. }
  882. kvm_arch_init_irq_routing(s);
  883. }
  884. void kvm_irqchip_commit_routes(KVMState *s)
  885. {
  886. int ret;
  887. if (kvm_gsi_direct_mapping()) {
  888. return;
  889. }
  890. if (!kvm_gsi_routing_enabled()) {
  891. return;
  892. }
  893. s->irq_routes->flags = 0;
  894. trace_kvm_irqchip_commit_routes();
  895. ret = kvm_vm_ioctl(s, KVM_SET_GSI_ROUTING, s->irq_routes);
  896. assert(ret == 0);
  897. }
  898. static void kvm_add_routing_entry(KVMState *s,
  899. struct kvm_irq_routing_entry *entry)
  900. {
  901. struct kvm_irq_routing_entry *new;
  902. int n, size;
  903. if (s->irq_routes->nr == s->nr_allocated_irq_routes) {
  904. n = s->nr_allocated_irq_routes * 2;
  905. if (n < 64) {
  906. n = 64;
  907. }
  908. size = sizeof(struct kvm_irq_routing);
  909. size += n * sizeof(*new);
  910. s->irq_routes = g_realloc(s->irq_routes, size);
  911. s->nr_allocated_irq_routes = n;
  912. }
  913. n = s->irq_routes->nr++;
  914. new = &s->irq_routes->entries[n];
  915. *new = *entry;
  916. set_gsi(s, entry->gsi);
  917. }
  918. static int kvm_update_routing_entry(KVMState *s,
  919. struct kvm_irq_routing_entry *new_entry)
  920. {
  921. struct kvm_irq_routing_entry *entry;
  922. int n;
  923. for (n = 0; n < s->irq_routes->nr; n++) {
  924. entry = &s->irq_routes->entries[n];
  925. if (entry->gsi != new_entry->gsi) {
  926. continue;
  927. }
  928. if(!memcmp(entry, new_entry, sizeof *entry)) {
  929. return 0;
  930. }
  931. *entry = *new_entry;
  932. return 0;
  933. }
  934. return -ESRCH;
  935. }
  936. void kvm_irqchip_add_irq_route(KVMState *s, int irq, int irqchip, int pin)
  937. {
  938. struct kvm_irq_routing_entry e = {};
  939. assert(pin < s->gsi_count);
  940. e.gsi = irq;
  941. e.type = KVM_IRQ_ROUTING_IRQCHIP;
  942. e.flags = 0;
  943. e.u.irqchip.irqchip = irqchip;
  944. e.u.irqchip.pin = pin;
  945. kvm_add_routing_entry(s, &e);
  946. }
  947. void kvm_irqchip_release_virq(KVMState *s, int virq)
  948. {
  949. struct kvm_irq_routing_entry *e;
  950. int i;
  951. if (kvm_gsi_direct_mapping()) {
  952. return;
  953. }
  954. for (i = 0; i < s->irq_routes->nr; i++) {
  955. e = &s->irq_routes->entries[i];
  956. if (e->gsi == virq) {
  957. s->irq_routes->nr--;
  958. *e = s->irq_routes->entries[s->irq_routes->nr];
  959. }
  960. }
  961. clear_gsi(s, virq);
  962. kvm_arch_release_virq_post(virq);
  963. }
  964. static unsigned int kvm_hash_msi(uint32_t data)
  965. {
  966. /* This is optimized for IA32 MSI layout. However, no other arch shall
  967. * repeat the mistake of not providing a direct MSI injection API. */
  968. return data & 0xff;
  969. }
  970. static void kvm_flush_dynamic_msi_routes(KVMState *s)
  971. {
  972. KVMMSIRoute *route, *next;
  973. unsigned int hash;
  974. for (hash = 0; hash < KVM_MSI_HASHTAB_SIZE; hash++) {
  975. QTAILQ_FOREACH_SAFE(route, &s->msi_hashtab[hash], entry, next) {
  976. kvm_irqchip_release_virq(s, route->kroute.gsi);
  977. QTAILQ_REMOVE(&s->msi_hashtab[hash], route, entry);
  978. g_free(route);
  979. }
  980. }
  981. }
  982. static int kvm_irqchip_get_virq(KVMState *s)
  983. {
  984. int next_virq;
  985. /*
  986. * PIC and IOAPIC share the first 16 GSI numbers, thus the available
  987. * GSI numbers are more than the number of IRQ route. Allocating a GSI
  988. * number can succeed even though a new route entry cannot be added.
  989. * When this happens, flush dynamic MSI entries to free IRQ route entries.
  990. */
  991. if (!kvm_direct_msi_allowed && s->irq_routes->nr == s->gsi_count) {
  992. kvm_flush_dynamic_msi_routes(s);
  993. }
  994. /* Return the lowest unused GSI in the bitmap */
  995. next_virq = find_first_zero_bit(s->used_gsi_bitmap, s->gsi_count);
  996. if (next_virq >= s->gsi_count) {
  997. return -ENOSPC;
  998. } else {
  999. return next_virq;
  1000. }
  1001. }
  1002. static KVMMSIRoute *kvm_lookup_msi_route(KVMState *s, MSIMessage msg)
  1003. {
  1004. unsigned int hash = kvm_hash_msi(msg.data);
  1005. KVMMSIRoute *route;
  1006. QTAILQ_FOREACH(route, &s->msi_hashtab[hash], entry) {
  1007. if (route->kroute.u.msi.address_lo == (uint32_t)msg.address &&
  1008. route->kroute.u.msi.address_hi == (msg.address >> 32) &&
  1009. route->kroute.u.msi.data == le32_to_cpu(msg.data)) {
  1010. return route;
  1011. }
  1012. }
  1013. return NULL;
  1014. }
  1015. int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
  1016. {
  1017. struct kvm_msi msi;
  1018. KVMMSIRoute *route;
  1019. if (kvm_direct_msi_allowed) {
  1020. msi.address_lo = (uint32_t)msg.address;
  1021. msi.address_hi = msg.address >> 32;
  1022. msi.data = le32_to_cpu(msg.data);
  1023. msi.flags = 0;
  1024. memset(msi.pad, 0, sizeof(msi.pad));
  1025. return kvm_vm_ioctl(s, KVM_SIGNAL_MSI, &msi);
  1026. }
  1027. route = kvm_lookup_msi_route(s, msg);
  1028. if (!route) {
  1029. int virq;
  1030. virq = kvm_irqchip_get_virq(s);
  1031. if (virq < 0) {
  1032. return virq;
  1033. }
  1034. route = g_malloc0(sizeof(KVMMSIRoute));
  1035. route->kroute.gsi = virq;
  1036. route->kroute.type = KVM_IRQ_ROUTING_MSI;
  1037. route->kroute.flags = 0;
  1038. route->kroute.u.msi.address_lo = (uint32_t)msg.address;
  1039. route->kroute.u.msi.address_hi = msg.address >> 32;
  1040. route->kroute.u.msi.data = le32_to_cpu(msg.data);
  1041. kvm_add_routing_entry(s, &route->kroute);
  1042. kvm_irqchip_commit_routes(s);
  1043. QTAILQ_INSERT_TAIL(&s->msi_hashtab[kvm_hash_msi(msg.data)], route,
  1044. entry);
  1045. }
  1046. assert(route->kroute.type == KVM_IRQ_ROUTING_MSI);
  1047. return kvm_set_irq(s, route->kroute.gsi, 1);
  1048. }
  1049. int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
  1050. {
  1051. struct kvm_irq_routing_entry kroute = {};
  1052. int virq;
  1053. MSIMessage msg = {0, 0};
  1054. if (dev) {
  1055. msg = pci_get_msi_message(dev, vector);
  1056. }
  1057. if (kvm_gsi_direct_mapping()) {
  1058. return kvm_arch_msi_data_to_gsi(msg.data);
  1059. }
  1060. if (!kvm_gsi_routing_enabled()) {
  1061. return -ENOSYS;
  1062. }
  1063. virq = kvm_irqchip_get_virq(s);
  1064. if (virq < 0) {
  1065. return virq;
  1066. }
  1067. kroute.gsi = virq;
  1068. kroute.type = KVM_IRQ_ROUTING_MSI;
  1069. kroute.flags = 0;
  1070. kroute.u.msi.address_lo = (uint32_t)msg.address;
  1071. kroute.u.msi.address_hi = msg.address >> 32;
  1072. kroute.u.msi.data = le32_to_cpu(msg.data);
  1073. if (kvm_msi_devid_required()) {
  1074. kroute.flags = KVM_MSI_VALID_DEVID;
  1075. kroute.u.msi.devid = pci_requester_id(dev);
  1076. }
  1077. if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
  1078. kvm_irqchip_release_virq(s, virq);
  1079. return -EINVAL;
  1080. }
  1081. trace_kvm_irqchip_add_msi_route(virq);
  1082. kvm_add_routing_entry(s, &kroute);
  1083. kvm_arch_add_msi_route_post(&kroute, vector, dev);
  1084. kvm_irqchip_commit_routes(s);
  1085. return virq;
  1086. }
  1087. int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg,
  1088. PCIDevice *dev)
  1089. {
  1090. struct kvm_irq_routing_entry kroute = {};
  1091. if (kvm_gsi_direct_mapping()) {
  1092. return 0;
  1093. }
  1094. if (!kvm_irqchip_in_kernel()) {
  1095. return -ENOSYS;
  1096. }
  1097. kroute.gsi = virq;
  1098. kroute.type = KVM_IRQ_ROUTING_MSI;
  1099. kroute.flags = 0;
  1100. kroute.u.msi.address_lo = (uint32_t)msg.address;
  1101. kroute.u.msi.address_hi = msg.address >> 32;
  1102. kroute.u.msi.data = le32_to_cpu(msg.data);
  1103. if (kvm_msi_devid_required()) {
  1104. kroute.flags = KVM_MSI_VALID_DEVID;
  1105. kroute.u.msi.devid = pci_requester_id(dev);
  1106. }
  1107. if (kvm_arch_fixup_msi_route(&kroute, msg.address, msg.data, dev)) {
  1108. return -EINVAL;
  1109. }
  1110. trace_kvm_irqchip_update_msi_route(virq);
  1111. return kvm_update_routing_entry(s, &kroute);
  1112. }
  1113. static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int rfd, int virq,
  1114. bool assign)
  1115. {
  1116. struct kvm_irqfd irqfd = {
  1117. .fd = fd,
  1118. .gsi = virq,
  1119. .flags = assign ? 0 : KVM_IRQFD_FLAG_DEASSIGN,
  1120. };
  1121. if (rfd != -1) {
  1122. irqfd.flags |= KVM_IRQFD_FLAG_RESAMPLE;
  1123. irqfd.resamplefd = rfd;
  1124. }
  1125. if (!kvm_irqfds_enabled()) {
  1126. return -ENOSYS;
  1127. }
  1128. return kvm_vm_ioctl(s, KVM_IRQFD, &irqfd);
  1129. }
  1130. int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
  1131. {
  1132. struct kvm_irq_routing_entry kroute = {};
  1133. int virq;
  1134. if (!kvm_gsi_routing_enabled()) {
  1135. return -ENOSYS;
  1136. }
  1137. virq = kvm_irqchip_get_virq(s);
  1138. if (virq < 0) {
  1139. return virq;
  1140. }
  1141. kroute.gsi = virq;
  1142. kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;
  1143. kroute.flags = 0;
  1144. kroute.u.adapter.summary_addr = adapter->summary_addr;
  1145. kroute.u.adapter.ind_addr = adapter->ind_addr;
  1146. kroute.u.adapter.summary_offset = adapter->summary_offset;
  1147. kroute.u.adapter.ind_offset = adapter->ind_offset;
  1148. kroute.u.adapter.adapter_id = adapter->adapter_id;
  1149. kvm_add_routing_entry(s, &kroute);
  1150. return virq;
  1151. }
  1152. int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
  1153. {
  1154. struct kvm_irq_routing_entry kroute = {};
  1155. int virq;
  1156. if (!kvm_gsi_routing_enabled()) {
  1157. return -ENOSYS;
  1158. }
  1159. if (!kvm_check_extension(s, KVM_CAP_HYPERV_SYNIC)) {
  1160. return -ENOSYS;
  1161. }
  1162. virq = kvm_irqchip_get_virq(s);
  1163. if (virq < 0) {
  1164. return virq;
  1165. }
  1166. kroute.gsi = virq;
  1167. kroute.type = KVM_IRQ_ROUTING_HV_SINT;
  1168. kroute.flags = 0;
  1169. kroute.u.hv_sint.vcpu = vcpu;
  1170. kroute.u.hv_sint.sint = sint;
  1171. kvm_add_routing_entry(s, &kroute);
  1172. kvm_irqchip_commit_routes(s);
  1173. return virq;
  1174. }
  1175. #else /* !KVM_CAP_IRQ_ROUTING */
  1176. void kvm_init_irq_routing(KVMState *s)
  1177. {
  1178. }
  1179. void kvm_irqchip_release_virq(KVMState *s, int virq)
  1180. {
  1181. }
  1182. int kvm_irqchip_send_msi(KVMState *s, MSIMessage msg)
  1183. {
  1184. abort();
  1185. }
  1186. int kvm_irqchip_add_msi_route(KVMState *s, int vector, PCIDevice *dev)
  1187. {
  1188. return -ENOSYS;
  1189. }
  1190. int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)
  1191. {
  1192. return -ENOSYS;
  1193. }
  1194. int kvm_irqchip_add_hv_sint_route(KVMState *s, uint32_t vcpu, uint32_t sint)
  1195. {
  1196. return -ENOSYS;
  1197. }
  1198. static int kvm_irqchip_assign_irqfd(KVMState *s, int fd, int virq, bool assign)
  1199. {
  1200. abort();
  1201. }
  1202. int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)
  1203. {
  1204. return -ENOSYS;
  1205. }
  1206. #endif /* !KVM_CAP_IRQ_ROUTING */
  1207. int kvm_irqchip_add_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
  1208. EventNotifier *rn, int virq)
  1209. {
  1210. return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n),
  1211. rn ? event_notifier_get_fd(rn) : -1, virq, true);
  1212. }
  1213. int kvm_irqchip_remove_irqfd_notifier_gsi(KVMState *s, EventNotifier *n,
  1214. int virq)
  1215. {
  1216. return kvm_irqchip_assign_irqfd(s, event_notifier_get_fd(n), -1, virq,
  1217. false);
  1218. }
  1219. int kvm_irqchip_add_irqfd_notifier(KVMState *s, EventNotifier *n,
  1220. EventNotifier *rn, qemu_irq irq)
  1221. {
  1222. gpointer key, gsi;
  1223. gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
  1224. if (!found) {
  1225. return -ENXIO;
  1226. }
  1227. return kvm_irqchip_add_irqfd_notifier_gsi(s, n, rn, GPOINTER_TO_INT(gsi));
  1228. }
  1229. int kvm_irqchip_remove_irqfd_notifier(KVMState *s, EventNotifier *n,
  1230. qemu_irq irq)
  1231. {
  1232. gpointer key, gsi;
  1233. gboolean found = g_hash_table_lookup_extended(s->gsimap, irq, &key, &gsi);
  1234. if (!found) {
  1235. return -ENXIO;
  1236. }
  1237. return kvm_irqchip_remove_irqfd_notifier_gsi(s, n, GPOINTER_TO_INT(gsi));
  1238. }
  1239. void kvm_irqchip_set_qemuirq_gsi(KVMState *s, qemu_irq irq, int gsi)
  1240. {
  1241. g_hash_table_insert(s->gsimap, irq, GINT_TO_POINTER(gsi));
  1242. }
  1243. static void kvm_irqchip_create(MachineState *machine, KVMState *s)
  1244. {
  1245. int ret;
  1246. if (kvm_check_extension(s, KVM_CAP_IRQCHIP)) {
  1247. ;
  1248. } else if (kvm_check_extension(s, KVM_CAP_S390_IRQCHIP)) {
  1249. ret = kvm_vm_enable_cap(s, KVM_CAP_S390_IRQCHIP, 0);
  1250. if (ret < 0) {
  1251. fprintf(stderr, "Enable kernel irqchip failed: %s\n", strerror(-ret));
  1252. exit(1);
  1253. }
  1254. } else {
  1255. return;
  1256. }
  1257. /* First probe and see if there's a arch-specific hook to create the
  1258. * in-kernel irqchip for us */
  1259. ret = kvm_arch_irqchip_create(machine, s);
  1260. if (ret == 0) {
  1261. if (machine_kernel_irqchip_split(machine)) {
  1262. perror("Split IRQ chip mode not supported.");
  1263. exit(1);
  1264. } else {
  1265. ret = kvm_vm_ioctl(s, KVM_CREATE_IRQCHIP);
  1266. }
  1267. }
  1268. if (ret < 0) {
  1269. fprintf(stderr, "Create kernel irqchip failed: %s\n", strerror(-ret));
  1270. exit(1);
  1271. }
  1272. kvm_kernel_irqchip = true;
  1273. /* If we have an in-kernel IRQ chip then we must have asynchronous
  1274. * interrupt delivery (though the reverse is not necessarily true)
  1275. */
  1276. kvm_async_interrupts_allowed = true;
  1277. kvm_halt_in_kernel_allowed = true;
  1278. kvm_init_irq_routing(s);
  1279. s->gsimap = g_hash_table_new(g_direct_hash, g_direct_equal);
  1280. }
  1281. /* Find number of supported CPUs using the recommended
  1282. * procedure from the kernel API documentation to cope with
  1283. * older kernels that may be missing capabilities.
  1284. */
  1285. static int kvm_recommended_vcpus(KVMState *s)
  1286. {
  1287. int ret = kvm_check_extension(s, KVM_CAP_NR_VCPUS);
  1288. return (ret) ? ret : 4;
  1289. }
  1290. static int kvm_max_vcpus(KVMState *s)
  1291. {
  1292. int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPUS);
  1293. return (ret) ? ret : kvm_recommended_vcpus(s);
  1294. }
  1295. static int kvm_max_vcpu_id(KVMState *s)
  1296. {
  1297. int ret = kvm_check_extension(s, KVM_CAP_MAX_VCPU_ID);
  1298. return (ret) ? ret : kvm_max_vcpus(s);
  1299. }
  1300. bool kvm_vcpu_id_is_valid(int vcpu_id)
  1301. {
  1302. KVMState *s = KVM_STATE(current_machine->accelerator);
  1303. return vcpu_id >= 0 && vcpu_id < kvm_max_vcpu_id(s);
  1304. }
  1305. static int kvm_init(MachineState *ms)
  1306. {
  1307. MachineClass *mc = MACHINE_GET_CLASS(ms);
  1308. static const char upgrade_note[] =
  1309. "Please upgrade to at least kernel 2.6.29 or recent kvm-kmod\n"
  1310. "(see http://sourceforge.net/projects/kvm).\n";
  1311. struct {
  1312. const char *name;
  1313. int num;
  1314. } num_cpus[] = {
  1315. { "SMP", smp_cpus },
  1316. { "hotpluggable", max_cpus },
  1317. { NULL, }
  1318. }, *nc = num_cpus;
  1319. int soft_vcpus_limit, hard_vcpus_limit;
  1320. KVMState *s;
  1321. const KVMCapabilityInfo *missing_cap;
  1322. int ret;
  1323. int type = 0;
  1324. const char *kvm_type;
  1325. s = KVM_STATE(ms->accelerator);
  1326. /*
  1327. * On systems where the kernel can support different base page
  1328. * sizes, host page size may be different from TARGET_PAGE_SIZE,
  1329. * even with KVM. TARGET_PAGE_SIZE is assumed to be the minimum
  1330. * page size for the system though.
  1331. */
  1332. assert(TARGET_PAGE_SIZE <= getpagesize());
  1333. s->sigmask_len = 8;
  1334. #ifdef KVM_CAP_SET_GUEST_DEBUG
  1335. QTAILQ_INIT(&s->kvm_sw_breakpoints);
  1336. #endif
  1337. QLIST_INIT(&s->kvm_parked_vcpus);
  1338. s->vmfd = -1;
  1339. s->fd = qemu_open("/dev/kvm", O_RDWR);
  1340. if (s->fd == -1) {
  1341. fprintf(stderr, "Could not access KVM kernel module: %m\n");
  1342. ret = -errno;
  1343. goto err;
  1344. }
  1345. ret = kvm_ioctl(s, KVM_GET_API_VERSION, 0);
  1346. if (ret < KVM_API_VERSION) {
  1347. if (ret >= 0) {
  1348. ret = -EINVAL;
  1349. }
  1350. fprintf(stderr, "kvm version too old\n");
  1351. goto err;
  1352. }
  1353. if (ret > KVM_API_VERSION) {
  1354. ret = -EINVAL;
  1355. fprintf(stderr, "kvm version not supported\n");
  1356. goto err;
  1357. }
  1358. s->nr_slots = kvm_check_extension(s, KVM_CAP_NR_MEMSLOTS);
  1359. /* If unspecified, use the default value */
  1360. if (!s->nr_slots) {
  1361. s->nr_slots = 32;
  1362. }
  1363. /* check the vcpu limits */
  1364. soft_vcpus_limit = kvm_recommended_vcpus(s);
  1365. hard_vcpus_limit = kvm_max_vcpus(s);
  1366. while (nc->name) {
  1367. if (nc->num > soft_vcpus_limit) {
  1368. fprintf(stderr,
  1369. "Warning: Number of %s cpus requested (%d) exceeds "
  1370. "the recommended cpus supported by KVM (%d)\n",
  1371. nc->name, nc->num, soft_vcpus_limit);
  1372. if (nc->num > hard_vcpus_limit) {
  1373. fprintf(stderr, "Number of %s cpus requested (%d) exceeds "
  1374. "the maximum cpus supported by KVM (%d)\n",
  1375. nc->name, nc->num, hard_vcpus_limit);
  1376. exit(1);
  1377. }
  1378. }
  1379. nc++;
  1380. }
  1381. kvm_type = qemu_opt_get(qemu_get_machine_opts(), "kvm-type");
  1382. if (mc->kvm_type) {
  1383. type = mc->kvm_type(kvm_type);
  1384. } else if (kvm_type) {
  1385. ret = -EINVAL;
  1386. fprintf(stderr, "Invalid argument kvm-type=%s\n", kvm_type);
  1387. goto err;
  1388. }
  1389. do {
  1390. ret = kvm_ioctl(s, KVM_CREATE_VM, type);
  1391. } while (ret == -EINTR);
  1392. if (ret < 0) {
  1393. fprintf(stderr, "ioctl(KVM_CREATE_VM) failed: %d %s\n", -ret,
  1394. strerror(-ret));
  1395. #ifdef TARGET_S390X
  1396. if (ret == -EINVAL) {
  1397. fprintf(stderr,
  1398. "Host kernel setup problem detected. Please verify:\n");
  1399. fprintf(stderr, "- for kernels supporting the switch_amode or"
  1400. " user_mode parameters, whether\n");
  1401. fprintf(stderr,
  1402. " user space is running in primary address space\n");
  1403. fprintf(stderr,
  1404. "- for kernels supporting the vm.allocate_pgste sysctl, "
  1405. "whether it is enabled\n");
  1406. }
  1407. #endif
  1408. goto err;
  1409. }
  1410. s->vmfd = ret;
  1411. missing_cap = kvm_check_extension_list(s, kvm_required_capabilites);
  1412. if (!missing_cap) {
  1413. missing_cap =
  1414. kvm_check_extension_list(s, kvm_arch_required_capabilities);
  1415. }
  1416. if (missing_cap) {
  1417. ret = -EINVAL;
  1418. fprintf(stderr, "kvm does not support %s\n%s",
  1419. missing_cap->name, upgrade_note);
  1420. goto err;
  1421. }
  1422. s->coalesced_mmio = kvm_check_extension(s, KVM_CAP_COALESCED_MMIO);
  1423. s->broken_set_mem_region = 1;
  1424. ret = kvm_check_extension(s, KVM_CAP_JOIN_MEMORY_REGIONS_WORKS);
  1425. if (ret > 0) {
  1426. s->broken_set_mem_region = 0;
  1427. }
  1428. #ifdef KVM_CAP_VCPU_EVENTS
  1429. s->vcpu_events = kvm_check_extension(s, KVM_CAP_VCPU_EVENTS);
  1430. #endif
  1431. s->robust_singlestep =
  1432. kvm_check_extension(s, KVM_CAP_X86_ROBUST_SINGLESTEP);
  1433. #ifdef KVM_CAP_DEBUGREGS
  1434. s->debugregs = kvm_check_extension(s, KVM_CAP_DEBUGREGS);
  1435. #endif
  1436. #ifdef KVM_CAP_IRQ_ROUTING
  1437. kvm_direct_msi_allowed = (kvm_check_extension(s, KVM_CAP_SIGNAL_MSI) > 0);
  1438. #endif
  1439. s->intx_set_mask = kvm_check_extension(s, KVM_CAP_PCI_2_3);
  1440. s->irq_set_ioctl = KVM_IRQ_LINE;
  1441. if (kvm_check_extension(s, KVM_CAP_IRQ_INJECT_STATUS)) {
  1442. s->irq_set_ioctl = KVM_IRQ_LINE_STATUS;
  1443. }
  1444. #ifdef KVM_CAP_READONLY_MEM
  1445. kvm_readonly_mem_allowed =
  1446. (kvm_check_extension(s, KVM_CAP_READONLY_MEM) > 0);
  1447. #endif
  1448. kvm_eventfds_allowed =
  1449. (kvm_check_extension(s, KVM_CAP_IOEVENTFD) > 0);
  1450. kvm_irqfds_allowed =
  1451. (kvm_check_extension(s, KVM_CAP_IRQFD) > 0);
  1452. kvm_resamplefds_allowed =
  1453. (kvm_check_extension(s, KVM_CAP_IRQFD_RESAMPLE) > 0);
  1454. kvm_vm_attributes_allowed =
  1455. (kvm_check_extension(s, KVM_CAP_VM_ATTRIBUTES) > 0);
  1456. kvm_ioeventfd_any_length_allowed =
  1457. (kvm_check_extension(s, KVM_CAP_IOEVENTFD_ANY_LENGTH) > 0);
  1458. ret = kvm_arch_init(ms, s);
  1459. if (ret < 0) {
  1460. goto err;
  1461. }
  1462. if (machine_kernel_irqchip_allowed(ms)) {
  1463. kvm_irqchip_create(ms, s);
  1464. }
  1465. kvm_state = s;
  1466. if (kvm_eventfds_allowed) {
  1467. s->memory_listener.listener.eventfd_add = kvm_mem_ioeventfd_add;
  1468. s->memory_listener.listener.eventfd_del = kvm_mem_ioeventfd_del;
  1469. }
  1470. s->memory_listener.listener.coalesced_mmio_add = kvm_coalesce_mmio_region;
  1471. s->memory_listener.listener.coalesced_mmio_del = kvm_uncoalesce_mmio_region;
  1472. kvm_memory_listener_register(s, &s->memory_listener,
  1473. &address_space_memory, 0);
  1474. memory_listener_register(&kvm_io_listener,
  1475. &address_space_io);
  1476. s->many_ioeventfds = kvm_check_many_ioeventfds();
  1477. cpu_interrupt_handler = kvm_handle_interrupt;
  1478. return 0;
  1479. err:
  1480. assert(ret < 0);
  1481. if (s->vmfd >= 0) {
  1482. close(s->vmfd);
  1483. }
  1484. if (s->fd != -1) {
  1485. close(s->fd);
  1486. }
  1487. g_free(s->memory_listener.slots);
  1488. return ret;
  1489. }
  1490. void kvm_set_sigmask_len(KVMState *s, unsigned int sigmask_len)
  1491. {
  1492. s->sigmask_len = sigmask_len;
  1493. }
  1494. static void kvm_handle_io(uint16_t port, MemTxAttrs attrs, void *data, int direction,
  1495. int size, uint32_t count)
  1496. {
  1497. int i;
  1498. uint8_t *ptr = data;
  1499. for (i = 0; i < count; i++) {
  1500. address_space_rw(&address_space_io, port, attrs,
  1501. ptr, size,
  1502. direction == KVM_EXIT_IO_OUT);
  1503. ptr += size;
  1504. }
  1505. }
  1506. static int kvm_handle_internal_error(CPUState *cpu, struct kvm_run *run)
  1507. {
  1508. fprintf(stderr, "KVM internal error. Suberror: %d\n",
  1509. run->internal.suberror);
  1510. if (kvm_check_extension(kvm_state, KVM_CAP_INTERNAL_ERROR_DATA)) {
  1511. int i;
  1512. for (i = 0; i < run->internal.ndata; ++i) {
  1513. fprintf(stderr, "extra data[%d]: %"PRIx64"\n",
  1514. i, (uint64_t)run->internal.data[i]);
  1515. }
  1516. }
  1517. if (run->internal.suberror == KVM_INTERNAL_ERROR_EMULATION) {
  1518. fprintf(stderr, "emulation failure\n");
  1519. if (!kvm_arch_stop_on_emulation_error(cpu)) {
  1520. cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
  1521. return EXCP_INTERRUPT;
  1522. }
  1523. }
  1524. /* FIXME: Should trigger a qmp message to let management know
  1525. * something went wrong.
  1526. */
  1527. return -1;
  1528. }
  1529. void kvm_flush_coalesced_mmio_buffer(void)
  1530. {
  1531. KVMState *s = kvm_state;
  1532. if (s->coalesced_flush_in_progress) {
  1533. return;
  1534. }
  1535. s->coalesced_flush_in_progress = true;
  1536. if (s->coalesced_mmio_ring) {
  1537. struct kvm_coalesced_mmio_ring *ring = s->coalesced_mmio_ring;
  1538. while (ring->first != ring->last) {
  1539. struct kvm_coalesced_mmio *ent;
  1540. ent = &ring->coalesced_mmio[ring->first];
  1541. cpu_physical_memory_write(ent->phys_addr, ent->data, ent->len);
  1542. smp_wmb();
  1543. ring->first = (ring->first + 1) % KVM_COALESCED_MMIO_MAX;
  1544. }
  1545. }
  1546. s->coalesced_flush_in_progress = false;
  1547. }
  1548. static void do_kvm_cpu_synchronize_state(CPUState *cpu, run_on_cpu_data arg)
  1549. {
  1550. if (!cpu->kvm_vcpu_dirty) {
  1551. kvm_arch_get_registers(cpu);
  1552. cpu->kvm_vcpu_dirty = true;
  1553. }
  1554. }
  1555. void kvm_cpu_synchronize_state(CPUState *cpu)
  1556. {
  1557. if (!cpu->kvm_vcpu_dirty) {
  1558. run_on_cpu(cpu, do_kvm_cpu_synchronize_state, RUN_ON_CPU_NULL);
  1559. }
  1560. }
  1561. static void do_kvm_cpu_synchronize_post_reset(CPUState *cpu, run_on_cpu_data arg)
  1562. {
  1563. kvm_arch_put_registers(cpu, KVM_PUT_RESET_STATE);
  1564. cpu->kvm_vcpu_dirty = false;
  1565. }
  1566. void kvm_cpu_synchronize_post_reset(CPUState *cpu)
  1567. {
  1568. run_on_cpu(cpu, do_kvm_cpu_synchronize_post_reset, RUN_ON_CPU_NULL);
  1569. }
  1570. static void do_kvm_cpu_synchronize_post_init(CPUState *cpu, run_on_cpu_data arg)
  1571. {
  1572. kvm_arch_put_registers(cpu, KVM_PUT_FULL_STATE);
  1573. cpu->kvm_vcpu_dirty = false;
  1574. }
  1575. void kvm_cpu_synchronize_post_init(CPUState *cpu)
  1576. {
  1577. run_on_cpu(cpu, do_kvm_cpu_synchronize_post_init, RUN_ON_CPU_NULL);
  1578. }
  1579. int kvm_cpu_exec(CPUState *cpu)
  1580. {
  1581. struct kvm_run *run = cpu->kvm_run;
  1582. int ret, run_ret;
  1583. DPRINTF("kvm_cpu_exec()\n");
  1584. if (kvm_arch_process_async_events(cpu)) {
  1585. cpu->exit_request = 0;
  1586. return EXCP_HLT;
  1587. }
  1588. qemu_mutex_unlock_iothread();
  1589. do {
  1590. MemTxAttrs attrs;
  1591. if (cpu->kvm_vcpu_dirty) {
  1592. kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);
  1593. cpu->kvm_vcpu_dirty = false;
  1594. }
  1595. kvm_arch_pre_run(cpu, run);
  1596. if (cpu->exit_request) {
  1597. DPRINTF("interrupt exit requested\n");
  1598. /*
  1599. * KVM requires us to reenter the kernel after IO exits to complete
  1600. * instruction emulation. This self-signal will ensure that we
  1601. * leave ASAP again.
  1602. */
  1603. qemu_cpu_kick_self();
  1604. }
  1605. run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
  1606. attrs = kvm_arch_post_run(cpu, run);
  1607. if (run_ret < 0) {
  1608. if (run_ret == -EINTR || run_ret == -EAGAIN) {
  1609. DPRINTF("io window exit\n");
  1610. ret = EXCP_INTERRUPT;
  1611. break;
  1612. }
  1613. fprintf(stderr, "error: kvm run failed %s\n",
  1614. strerror(-run_ret));
  1615. #ifdef TARGET_PPC
  1616. if (run_ret == -EBUSY) {
  1617. fprintf(stderr,
  1618. "This is probably because your SMT is enabled.\n"
  1619. "VCPU can only run on primary threads with all "
  1620. "secondary threads offline.\n");
  1621. }
  1622. #endif
  1623. ret = -1;
  1624. break;
  1625. }
  1626. trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);
  1627. switch (run->exit_reason) {
  1628. case KVM_EXIT_IO:
  1629. DPRINTF("handle_io\n");
  1630. /* Called outside BQL */
  1631. kvm_handle_io(run->io.port, attrs,
  1632. (uint8_t *)run + run->io.data_offset,
  1633. run->io.direction,
  1634. run->io.size,
  1635. run->io.count);
  1636. ret = 0;
  1637. break;
  1638. case KVM_EXIT_MMIO:
  1639. DPRINTF("handle_mmio\n");
  1640. /* Called outside BQL */
  1641. address_space_rw(&address_space_memory,
  1642. run->mmio.phys_addr, attrs,
  1643. run->mmio.data,
  1644. run->mmio.len,
  1645. run->mmio.is_write);
  1646. ret = 0;
  1647. break;
  1648. case KVM_EXIT_IRQ_WINDOW_OPEN:
  1649. DPRINTF("irq_window_open\n");
  1650. ret = EXCP_INTERRUPT;
  1651. break;
  1652. case KVM_EXIT_SHUTDOWN:
  1653. DPRINTF("shutdown\n");
  1654. qemu_system_reset_request();
  1655. ret = EXCP_INTERRUPT;
  1656. break;
  1657. case KVM_EXIT_UNKNOWN:
  1658. fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",
  1659. (uint64_t)run->hw.hardware_exit_reason);
  1660. ret = -1;
  1661. break;
  1662. case KVM_EXIT_INTERNAL_ERROR:
  1663. ret = kvm_handle_internal_error(cpu, run);
  1664. break;
  1665. case KVM_EXIT_SYSTEM_EVENT:
  1666. switch (run->system_event.type) {
  1667. case KVM_SYSTEM_EVENT_SHUTDOWN:
  1668. qemu_system_shutdown_request();
  1669. ret = EXCP_INTERRUPT;
  1670. break;
  1671. case KVM_SYSTEM_EVENT_RESET:
  1672. qemu_system_reset_request();
  1673. ret = EXCP_INTERRUPT;
  1674. break;
  1675. case KVM_SYSTEM_EVENT_CRASH:
  1676. qemu_mutex_lock_iothread();
  1677. qemu_system_guest_panicked();
  1678. qemu_mutex_unlock_iothread();
  1679. ret = 0;
  1680. break;
  1681. default:
  1682. DPRINTF("kvm_arch_handle_exit\n");
  1683. ret = kvm_arch_handle_exit(cpu, run);
  1684. break;
  1685. }
  1686. break;
  1687. default:
  1688. DPRINTF("kvm_arch_handle_exit\n");
  1689. ret = kvm_arch_handle_exit(cpu, run);
  1690. break;
  1691. }
  1692. } while (ret == 0);
  1693. qemu_mutex_lock_iothread();
  1694. if (ret < 0) {
  1695. cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);
  1696. vm_stop(RUN_STATE_INTERNAL_ERROR);
  1697. }
  1698. cpu->exit_request = 0;
  1699. return ret;
  1700. }
  1701. int kvm_ioctl(KVMState *s, int type, ...)
  1702. {
  1703. int ret;
  1704. void *arg;
  1705. va_list ap;
  1706. va_start(ap, type);
  1707. arg = va_arg(ap, void *);
  1708. va_end(ap);
  1709. trace_kvm_ioctl(type, arg);
  1710. ret = ioctl(s->fd, type, arg);
  1711. if (ret == -1) {
  1712. ret = -errno;
  1713. }
  1714. return ret;
  1715. }
  1716. int kvm_vm_ioctl(KVMState *s, int type, ...)
  1717. {
  1718. int ret;
  1719. void *arg;
  1720. va_list ap;
  1721. va_start(ap, type);
  1722. arg = va_arg(ap, void *);
  1723. va_end(ap);
  1724. trace_kvm_vm_ioctl(type, arg);
  1725. ret = ioctl(s->vmfd, type, arg);
  1726. if (ret == -1) {
  1727. ret = -errno;
  1728. }
  1729. return ret;
  1730. }
  1731. int kvm_vcpu_ioctl(CPUState *cpu, int type, ...)
  1732. {
  1733. int ret;
  1734. void *arg;
  1735. va_list ap;
  1736. va_start(ap, type);
  1737. arg = va_arg(ap, void *);
  1738. va_end(ap);
  1739. trace_kvm_vcpu_ioctl(cpu->cpu_index, type, arg);
  1740. ret = ioctl(cpu->kvm_fd, type, arg);
  1741. if (ret == -1) {
  1742. ret = -errno;
  1743. }
  1744. return ret;
  1745. }
  1746. int kvm_device_ioctl(int fd, int type, ...)
  1747. {
  1748. int ret;
  1749. void *arg;
  1750. va_list ap;
  1751. va_start(ap, type);
  1752. arg = va_arg(ap, void *);
  1753. va_end(ap);
  1754. trace_kvm_device_ioctl(fd, type, arg);
  1755. ret = ioctl(fd, type, arg);
  1756. if (ret == -1) {
  1757. ret = -errno;
  1758. }
  1759. return ret;
  1760. }
  1761. int kvm_vm_check_attr(KVMState *s, uint32_t group, uint64_t attr)
  1762. {
  1763. int ret;
  1764. struct kvm_device_attr attribute = {
  1765. .group = group,
  1766. .attr = attr,
  1767. };
  1768. if (!kvm_vm_attributes_allowed) {
  1769. return 0;
  1770. }
  1771. ret = kvm_vm_ioctl(s, KVM_HAS_DEVICE_ATTR, &attribute);
  1772. /* kvm returns 0 on success for HAS_DEVICE_ATTR */
  1773. return ret ? 0 : 1;
  1774. }
  1775. int kvm_device_check_attr(int dev_fd, uint32_t group, uint64_t attr)
  1776. {
  1777. struct kvm_device_attr attribute = {
  1778. .group = group,
  1779. .attr = attr,
  1780. .flags = 0,
  1781. };
  1782. return kvm_device_ioctl(dev_fd, KVM_HAS_DEVICE_ATTR, &attribute) ? 0 : 1;
  1783. }
  1784. void kvm_device_access(int fd, int group, uint64_t attr,
  1785. void *val, bool write)
  1786. {
  1787. struct kvm_device_attr kvmattr;
  1788. int err;
  1789. kvmattr.flags = 0;
  1790. kvmattr.group = group;
  1791. kvmattr.attr = attr;
  1792. kvmattr.addr = (uintptr_t)val;
  1793. err = kvm_device_ioctl(fd,
  1794. write ? KVM_SET_DEVICE_ATTR : KVM_GET_DEVICE_ATTR,
  1795. &kvmattr);
  1796. if (err < 0) {
  1797. error_report("KVM_%s_DEVICE_ATTR failed: %s",
  1798. write ? "SET" : "GET", strerror(-err));
  1799. error_printf("Group %d attr 0x%016" PRIx64 "\n", group, attr);
  1800. abort();
  1801. }
  1802. }
  1803. /* Return 1 on success, 0 on failure */
  1804. int kvm_has_sync_mmu(void)
  1805. {
  1806. return kvm_check_extension(kvm_state, KVM_CAP_SYNC_MMU);
  1807. }
  1808. int kvm_has_vcpu_events(void)
  1809. {
  1810. return kvm_state->vcpu_events;
  1811. }
  1812. int kvm_has_robust_singlestep(void)
  1813. {
  1814. return kvm_state->robust_singlestep;
  1815. }
  1816. int kvm_has_debugregs(void)
  1817. {
  1818. return kvm_state->debugregs;
  1819. }
  1820. int kvm_has_many_ioeventfds(void)
  1821. {
  1822. if (!kvm_enabled()) {
  1823. return 0;
  1824. }
  1825. return kvm_state->many_ioeventfds;
  1826. }
  1827. int kvm_has_gsi_routing(void)
  1828. {
  1829. #ifdef KVM_CAP_IRQ_ROUTING
  1830. return kvm_check_extension(kvm_state, KVM_CAP_IRQ_ROUTING);
  1831. #else
  1832. return false;
  1833. #endif
  1834. }
  1835. int kvm_has_intx_set_mask(void)
  1836. {
  1837. return kvm_state->intx_set_mask;
  1838. }
  1839. #ifdef KVM_CAP_SET_GUEST_DEBUG
  1840. struct kvm_sw_breakpoint *kvm_find_sw_breakpoint(CPUState *cpu,
  1841. target_ulong pc)
  1842. {
  1843. struct kvm_sw_breakpoint *bp;
  1844. QTAILQ_FOREACH(bp, &cpu->kvm_state->kvm_sw_breakpoints, entry) {
  1845. if (bp->pc == pc) {
  1846. return bp;
  1847. }
  1848. }
  1849. return NULL;
  1850. }
  1851. int kvm_sw_breakpoints_active(CPUState *cpu)
  1852. {
  1853. return !QTAILQ_EMPTY(&cpu->kvm_state->kvm_sw_breakpoints);
  1854. }
  1855. struct kvm_set_guest_debug_data {
  1856. struct kvm_guest_debug dbg;
  1857. int err;
  1858. };
  1859. static void kvm_invoke_set_guest_debug(CPUState *cpu, run_on_cpu_data data)
  1860. {
  1861. struct kvm_set_guest_debug_data *dbg_data =
  1862. (struct kvm_set_guest_debug_data *) data.host_ptr;
  1863. dbg_data->err = kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG,
  1864. &dbg_data->dbg);
  1865. }
  1866. int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
  1867. {
  1868. struct kvm_set_guest_debug_data data;
  1869. data.dbg.control = reinject_trap;
  1870. if (cpu->singlestep_enabled) {
  1871. data.dbg.control |= KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
  1872. }
  1873. kvm_arch_update_guest_debug(cpu, &data.dbg);
  1874. run_on_cpu(cpu, kvm_invoke_set_guest_debug,
  1875. RUN_ON_CPU_HOST_PTR(&data));
  1876. return data.err;
  1877. }
  1878. int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
  1879. target_ulong len, int type)
  1880. {
  1881. struct kvm_sw_breakpoint *bp;
  1882. int err;
  1883. if (type == GDB_BREAKPOINT_SW) {
  1884. bp = kvm_find_sw_breakpoint(cpu, addr);
  1885. if (bp) {
  1886. bp->use_count++;
  1887. return 0;
  1888. }
  1889. bp = g_malloc(sizeof(struct kvm_sw_breakpoint));
  1890. bp->pc = addr;
  1891. bp->use_count = 1;
  1892. err = kvm_arch_insert_sw_breakpoint(cpu, bp);
  1893. if (err) {
  1894. g_free(bp);
  1895. return err;
  1896. }
  1897. QTAILQ_INSERT_HEAD(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
  1898. } else {
  1899. err = kvm_arch_insert_hw_breakpoint(addr, len, type);
  1900. if (err) {
  1901. return err;
  1902. }
  1903. }
  1904. CPU_FOREACH(cpu) {
  1905. err = kvm_update_guest_debug(cpu, 0);
  1906. if (err) {
  1907. return err;
  1908. }
  1909. }
  1910. return 0;
  1911. }
  1912. int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
  1913. target_ulong len, int type)
  1914. {
  1915. struct kvm_sw_breakpoint *bp;
  1916. int err;
  1917. if (type == GDB_BREAKPOINT_SW) {
  1918. bp = kvm_find_sw_breakpoint(cpu, addr);
  1919. if (!bp) {
  1920. return -ENOENT;
  1921. }
  1922. if (bp->use_count > 1) {
  1923. bp->use_count--;
  1924. return 0;
  1925. }
  1926. err = kvm_arch_remove_sw_breakpoint(cpu, bp);
  1927. if (err) {
  1928. return err;
  1929. }
  1930. QTAILQ_REMOVE(&cpu->kvm_state->kvm_sw_breakpoints, bp, entry);
  1931. g_free(bp);
  1932. } else {
  1933. err = kvm_arch_remove_hw_breakpoint(addr, len, type);
  1934. if (err) {
  1935. return err;
  1936. }
  1937. }
  1938. CPU_FOREACH(cpu) {
  1939. err = kvm_update_guest_debug(cpu, 0);
  1940. if (err) {
  1941. return err;
  1942. }
  1943. }
  1944. return 0;
  1945. }
  1946. void kvm_remove_all_breakpoints(CPUState *cpu)
  1947. {
  1948. struct kvm_sw_breakpoint *bp, *next;
  1949. KVMState *s = cpu->kvm_state;
  1950. CPUState *tmpcpu;
  1951. QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {
  1952. if (kvm_arch_remove_sw_breakpoint(cpu, bp) != 0) {
  1953. /* Try harder to find a CPU that currently sees the breakpoint. */
  1954. CPU_FOREACH(tmpcpu) {
  1955. if (kvm_arch_remove_sw_breakpoint(tmpcpu, bp) == 0) {
  1956. break;
  1957. }
  1958. }
  1959. }
  1960. QTAILQ_REMOVE(&s->kvm_sw_breakpoints, bp, entry);
  1961. g_free(bp);
  1962. }
  1963. kvm_arch_remove_all_hw_breakpoints();
  1964. CPU_FOREACH(cpu) {
  1965. kvm_update_guest_debug(cpu, 0);
  1966. }
  1967. }
  1968. #else /* !KVM_CAP_SET_GUEST_DEBUG */
  1969. int kvm_update_guest_debug(CPUState *cpu, unsigned long reinject_trap)
  1970. {
  1971. return -EINVAL;
  1972. }
  1973. int kvm_insert_breakpoint(CPUState *cpu, target_ulong addr,
  1974. target_ulong len, int type)
  1975. {
  1976. return -EINVAL;
  1977. }
  1978. int kvm_remove_breakpoint(CPUState *cpu, target_ulong addr,
  1979. target_ulong len, int type)
  1980. {
  1981. return -EINVAL;
  1982. }
  1983. void kvm_remove_all_breakpoints(CPUState *cpu)
  1984. {
  1985. }
  1986. #endif /* !KVM_CAP_SET_GUEST_DEBUG */
  1987. int kvm_set_signal_mask(CPUState *cpu, const sigset_t *sigset)
  1988. {
  1989. KVMState *s = kvm_state;
  1990. struct kvm_signal_mask *sigmask;
  1991. int r;
  1992. if (!sigset) {
  1993. return kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, NULL);
  1994. }
  1995. sigmask = g_malloc(sizeof(*sigmask) + sizeof(*sigset));
  1996. sigmask->len = s->sigmask_len;
  1997. memcpy(sigmask->sigset, sigset, sizeof(*sigset));
  1998. r = kvm_vcpu_ioctl(cpu, KVM_SET_SIGNAL_MASK, sigmask);
  1999. g_free(sigmask);
  2000. return r;
  2001. }
  2002. int kvm_on_sigbus_vcpu(CPUState *cpu, int code, void *addr)
  2003. {
  2004. return kvm_arch_on_sigbus_vcpu(cpu, code, addr);
  2005. }
  2006. int kvm_on_sigbus(int code, void *addr)
  2007. {
  2008. return kvm_arch_on_sigbus(code, addr);
  2009. }
  2010. int kvm_create_device(KVMState *s, uint64_t type, bool test)
  2011. {
  2012. int ret;
  2013. struct kvm_create_device create_dev;
  2014. create_dev.type = type;
  2015. create_dev.fd = -1;
  2016. create_dev.flags = test ? KVM_CREATE_DEVICE_TEST : 0;
  2017. if (!kvm_check_extension(s, KVM_CAP_DEVICE_CTRL)) {
  2018. return -ENOTSUP;
  2019. }
  2020. ret = kvm_vm_ioctl(s, KVM_CREATE_DEVICE, &create_dev);
  2021. if (ret) {
  2022. return ret;
  2023. }
  2024. return test ? 0 : create_dev.fd;
  2025. }
  2026. bool kvm_device_supported(int vmfd, uint64_t type)
  2027. {
  2028. struct kvm_create_device create_dev = {
  2029. .type = type,
  2030. .fd = -1,
  2031. .flags = KVM_CREATE_DEVICE_TEST,
  2032. };
  2033. if (ioctl(vmfd, KVM_CHECK_EXTENSION, KVM_CAP_DEVICE_CTRL) <= 0) {
  2034. return false;
  2035. }
  2036. return (ioctl(vmfd, KVM_CREATE_DEVICE, &create_dev) >= 0);
  2037. }
  2038. int kvm_set_one_reg(CPUState *cs, uint64_t id, void *source)
  2039. {
  2040. struct kvm_one_reg reg;
  2041. int r;
  2042. reg.id = id;
  2043. reg.addr = (uintptr_t) source;
  2044. r = kvm_vcpu_ioctl(cs, KVM_SET_ONE_REG, &reg);
  2045. if (r) {
  2046. trace_kvm_failed_reg_set(id, strerror(-r));
  2047. }
  2048. return r;
  2049. }
  2050. int kvm_get_one_reg(CPUState *cs, uint64_t id, void *target)
  2051. {
  2052. struct kvm_one_reg reg;
  2053. int r;
  2054. reg.id = id;
  2055. reg.addr = (uintptr_t) target;
  2056. r = kvm_vcpu_ioctl(cs, KVM_GET_ONE_REG, &reg);
  2057. if (r) {
  2058. trace_kvm_failed_reg_get(id, strerror(-r));
  2059. }
  2060. return r;
  2061. }
  2062. static void kvm_accel_class_init(ObjectClass *oc, void *data)
  2063. {
  2064. AccelClass *ac = ACCEL_CLASS(oc);
  2065. ac->name = "KVM";
  2066. ac->init_machine = kvm_init;
  2067. ac->allowed = &kvm_allowed;
  2068. }
  2069. static const TypeInfo kvm_accel_type = {
  2070. .name = TYPE_KVM_ACCEL,
  2071. .parent = TYPE_ACCEL,
  2072. .class_init = kvm_accel_class_init,
  2073. .instance_size = sizeof(KVMState),
  2074. };
  2075. static void kvm_type_init(void)
  2076. {
  2077. type_register_static(&kvm_accel_type);
  2078. }
  2079. type_init(kvm_type_init);