]> Git Repo - qemu.git/blob - hw/i386/amd_iommu.c
x86_iommu/amd: Prepare for interrupt remap support
[qemu.git] / hw / i386 / amd_iommu.c
1 /*
2  * QEMU emulation of AMD IOMMU (AMD-Vi)
3  *
4  * Copyright (C) 2011 Eduard - Gabriel Munteanu
5  * Copyright (C) 2015 David Kiarie, <[email protected]>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, see <http://www.gnu.org/licenses/>.
19  *
20  * Cache implementation inspired by hw/i386/intel_iommu.c
21  */
22 #include "qemu/osdep.h"
23 #include "hw/i386/pc.h"
24 #include "hw/pci/msi.h"
25 #include "hw/pci/pci_bus.h"
26 #include "amd_iommu.h"
27 #include "qapi/error.h"
28 #include "qemu/error-report.h"
29 #include "hw/i386/apic_internal.h"
30 #include "trace.h"
31
32 /* used AMD-Vi MMIO registers */
33 const char *amdvi_mmio_low[] = {
34     "AMDVI_MMIO_DEVTAB_BASE",
35     "AMDVI_MMIO_CMDBUF_BASE",
36     "AMDVI_MMIO_EVTLOG_BASE",
37     "AMDVI_MMIO_CONTROL",
38     "AMDVI_MMIO_EXCL_BASE",
39     "AMDVI_MMIO_EXCL_LIMIT",
40     "AMDVI_MMIO_EXT_FEATURES",
41     "AMDVI_MMIO_PPR_BASE",
42     "UNHANDLED"
43 };
44 const char *amdvi_mmio_high[] = {
45     "AMDVI_MMIO_COMMAND_HEAD",
46     "AMDVI_MMIO_COMMAND_TAIL",
47     "AMDVI_MMIO_EVTLOG_HEAD",
48     "AMDVI_MMIO_EVTLOG_TAIL",
49     "AMDVI_MMIO_STATUS",
50     "AMDVI_MMIO_PPR_HEAD",
51     "AMDVI_MMIO_PPR_TAIL",
52     "UNHANDLED"
53 };
54
55 struct AMDVIAddressSpace {
56     uint8_t bus_num;            /* bus number                           */
57     uint8_t devfn;              /* device function                      */
58     AMDVIState *iommu_state;    /* AMDVI - one per machine              */
59     MemoryRegion root;          /* AMDVI Root memory map region */
60     IOMMUMemoryRegion iommu;    /* Device's address translation region  */
61     MemoryRegion iommu_ir;      /* Device's interrupt remapping region  */
62     AddressSpace as;            /* device's corresponding address space */
63 };
64
65 /* AMDVI cache entry */
66 typedef struct AMDVIIOTLBEntry {
67     uint16_t domid;             /* assigned domain id  */
68     uint16_t devid;             /* device owning entry */
69     uint64_t perms;             /* access permissions  */
70     uint64_t translated_addr;   /* translated address  */
71     uint64_t page_mask;         /* physical page size  */
72 } AMDVIIOTLBEntry;
73
74 /* configure MMIO registers at startup/reset */
75 static void amdvi_set_quad(AMDVIState *s, hwaddr addr, uint64_t val,
76                            uint64_t romask, uint64_t w1cmask)
77 {
78     stq_le_p(&s->mmior[addr], val);
79     stq_le_p(&s->romask[addr], romask);
80     stq_le_p(&s->w1cmask[addr], w1cmask);
81 }
82
83 static uint16_t amdvi_readw(AMDVIState *s, hwaddr addr)
84 {
85     return lduw_le_p(&s->mmior[addr]);
86 }
87
88 static uint32_t amdvi_readl(AMDVIState *s, hwaddr addr)
89 {
90     return ldl_le_p(&s->mmior[addr]);
91 }
92
93 static uint64_t amdvi_readq(AMDVIState *s, hwaddr addr)
94 {
95     return ldq_le_p(&s->mmior[addr]);
96 }
97
98 /* internal write */
99 static void amdvi_writeq_raw(AMDVIState *s, uint64_t val, hwaddr addr)
100 {
101     stq_le_p(&s->mmior[addr], val);
102 }
103
104 /* external write */
105 static void amdvi_writew(AMDVIState *s, hwaddr addr, uint16_t val)
106 {
107     uint16_t romask = lduw_le_p(&s->romask[addr]);
108     uint16_t w1cmask = lduw_le_p(&s->w1cmask[addr]);
109     uint16_t oldval = lduw_le_p(&s->mmior[addr]);
110     stw_le_p(&s->mmior[addr],
111             ((oldval & romask) | (val & ~romask)) & ~(val & w1cmask));
112 }
113
114 static void amdvi_writel(AMDVIState *s, hwaddr addr, uint32_t val)
115 {
116     uint32_t romask = ldl_le_p(&s->romask[addr]);
117     uint32_t w1cmask = ldl_le_p(&s->w1cmask[addr]);
118     uint32_t oldval = ldl_le_p(&s->mmior[addr]);
119     stl_le_p(&s->mmior[addr],
120             ((oldval & romask) | (val & ~romask)) & ~(val & w1cmask));
121 }
122
123 static void amdvi_writeq(AMDVIState *s, hwaddr addr, uint64_t val)
124 {
125     uint64_t romask = ldq_le_p(&s->romask[addr]);
126     uint64_t w1cmask = ldq_le_p(&s->w1cmask[addr]);
127     uint32_t oldval = ldq_le_p(&s->mmior[addr]);
128     stq_le_p(&s->mmior[addr],
129             ((oldval & romask) | (val & ~romask)) & ~(val & w1cmask));
130 }
131
132 /* OR a 64-bit register with a 64-bit value */
133 static bool amdvi_test_mask(AMDVIState *s, hwaddr addr, uint64_t val)
134 {
135     return amdvi_readq(s, addr) | val;
136 }
137
138 /* OR a 64-bit register with a 64-bit value storing result in the register */
139 static void amdvi_assign_orq(AMDVIState *s, hwaddr addr, uint64_t val)
140 {
141     amdvi_writeq_raw(s, addr, amdvi_readq(s, addr) | val);
142 }
143
144 /* AND a 64-bit register with a 64-bit value storing result in the register */
145 static void amdvi_assign_andq(AMDVIState *s, hwaddr addr, uint64_t val)
146 {
147    amdvi_writeq_raw(s, addr, amdvi_readq(s, addr) & val);
148 }
149
150 static void amdvi_generate_msi_interrupt(AMDVIState *s)
151 {
152     MSIMessage msg = {};
153     MemTxAttrs attrs = {
154         .requester_id = pci_requester_id(&s->pci.dev)
155     };
156
157     if (msi_enabled(&s->pci.dev)) {
158         msg = msi_get_message(&s->pci.dev, 0);
159         address_space_stl_le(&address_space_memory, msg.address, msg.data,
160                              attrs, NULL);
161     }
162 }
163
164 static void amdvi_log_event(AMDVIState *s, uint64_t *evt)
165 {
166     /* event logging not enabled */
167     if (!s->evtlog_enabled || amdvi_test_mask(s, AMDVI_MMIO_STATUS,
168         AMDVI_MMIO_STATUS_EVT_OVF)) {
169         return;
170     }
171
172     /* event log buffer full */
173     if (s->evtlog_tail >= s->evtlog_len) {
174         amdvi_assign_orq(s, AMDVI_MMIO_STATUS, AMDVI_MMIO_STATUS_EVT_OVF);
175         /* generate interrupt */
176         amdvi_generate_msi_interrupt(s);
177         return;
178     }
179
180     if (dma_memory_write(&address_space_memory, s->evtlog + s->evtlog_tail,
181         &evt, AMDVI_EVENT_LEN)) {
182         trace_amdvi_evntlog_fail(s->evtlog, s->evtlog_tail);
183     }
184
185     s->evtlog_tail += AMDVI_EVENT_LEN;
186     amdvi_assign_orq(s, AMDVI_MMIO_STATUS, AMDVI_MMIO_STATUS_COMP_INT);
187     amdvi_generate_msi_interrupt(s);
188 }
189
190 static void amdvi_setevent_bits(uint64_t *buffer, uint64_t value, int start,
191                                 int length)
192 {
193     int index = start / 64, bitpos = start % 64;
194     uint64_t mask = MAKE_64BIT_MASK(start, length);
195     buffer[index] &= ~mask;
196     buffer[index] |= (value << bitpos) & mask;
197 }
198 /*
199  * AMDVi event structure
200  *    0:15   -> DeviceID
201  *    55:63  -> event type + miscellaneous info
202  *    63:127 -> related address
203  */
204 static void amdvi_encode_event(uint64_t *evt, uint16_t devid, uint64_t addr,
205                                uint16_t info)
206 {
207     amdvi_setevent_bits(evt, devid, 0, 16);
208     amdvi_setevent_bits(evt, info, 55, 8);
209     amdvi_setevent_bits(evt, addr, 63, 64);
210 }
211 /* log an error encountered during a page walk
212  *
213  * @addr: virtual address in translation request
214  */
215 static void amdvi_page_fault(AMDVIState *s, uint16_t devid,
216                              hwaddr addr, uint16_t info)
217 {
218     uint64_t evt[4];
219
220     info |= AMDVI_EVENT_IOPF_I | AMDVI_EVENT_IOPF;
221     amdvi_encode_event(evt, devid, addr, info);
222     amdvi_log_event(s, evt);
223     pci_word_test_and_set_mask(s->pci.dev.config + PCI_STATUS,
224             PCI_STATUS_SIG_TARGET_ABORT);
225 }
226 /*
227  * log a master abort accessing device table
228  *  @devtab : address of device table entry
229  *  @info : error flags
230  */
231 static void amdvi_log_devtab_error(AMDVIState *s, uint16_t devid,
232                                    hwaddr devtab, uint16_t info)
233 {
234     uint64_t evt[4];
235
236     info |= AMDVI_EVENT_DEV_TAB_HW_ERROR;
237
238     amdvi_encode_event(evt, devid, devtab, info);
239     amdvi_log_event(s, evt);
240     pci_word_test_and_set_mask(s->pci.dev.config + PCI_STATUS,
241             PCI_STATUS_SIG_TARGET_ABORT);
242 }
243 /* log an event trying to access command buffer
244  *   @addr : address that couldn't be accessed
245  */
246 static void amdvi_log_command_error(AMDVIState *s, hwaddr addr)
247 {
248     uint64_t evt[4], info = AMDVI_EVENT_COMMAND_HW_ERROR;
249
250     amdvi_encode_event(evt, 0, addr, info);
251     amdvi_log_event(s, evt);
252     pci_word_test_and_set_mask(s->pci.dev.config + PCI_STATUS,
253             PCI_STATUS_SIG_TARGET_ABORT);
254 }
255 /* log an illegal comand event
256  *   @addr : address of illegal command
257  */
258 static void amdvi_log_illegalcom_error(AMDVIState *s, uint16_t info,
259                                        hwaddr addr)
260 {
261     uint64_t evt[4];
262
263     info |= AMDVI_EVENT_ILLEGAL_COMMAND_ERROR;
264     amdvi_encode_event(evt, 0, addr, info);
265     amdvi_log_event(s, evt);
266 }
267 /* log an error accessing device table
268  *
269  *  @devid : device owning the table entry
270  *  @devtab : address of device table entry
271  *  @info : error flags
272  */
273 static void amdvi_log_illegaldevtab_error(AMDVIState *s, uint16_t devid,
274                                           hwaddr addr, uint16_t info)
275 {
276     uint64_t evt[4];
277
278     info |= AMDVI_EVENT_ILLEGAL_DEVTAB_ENTRY;
279     amdvi_encode_event(evt, devid, addr, info);
280     amdvi_log_event(s, evt);
281 }
282 /* log an error accessing a PTE entry
283  * @addr : address that couldn't be accessed
284  */
285 static void amdvi_log_pagetab_error(AMDVIState *s, uint16_t devid,
286                                     hwaddr addr, uint16_t info)
287 {
288     uint64_t evt[4];
289
290     info |= AMDVI_EVENT_PAGE_TAB_HW_ERROR;
291     amdvi_encode_event(evt, devid, addr, info);
292     amdvi_log_event(s, evt);
293     pci_word_test_and_set_mask(s->pci.dev.config + PCI_STATUS,
294              PCI_STATUS_SIG_TARGET_ABORT);
295 }
296
297 static gboolean amdvi_uint64_equal(gconstpointer v1, gconstpointer v2)
298 {
299     return *((const uint64_t *)v1) == *((const uint64_t *)v2);
300 }
301
302 static guint amdvi_uint64_hash(gconstpointer v)
303 {
304     return (guint)*(const uint64_t *)v;
305 }
306
307 static AMDVIIOTLBEntry *amdvi_iotlb_lookup(AMDVIState *s, hwaddr addr,
308                                            uint64_t devid)
309 {
310     uint64_t key = (addr >> AMDVI_PAGE_SHIFT_4K) |
311                    ((uint64_t)(devid) << AMDVI_DEVID_SHIFT);
312     return g_hash_table_lookup(s->iotlb, &key);
313 }
314
315 static void amdvi_iotlb_reset(AMDVIState *s)
316 {
317     assert(s->iotlb);
318     trace_amdvi_iotlb_reset();
319     g_hash_table_remove_all(s->iotlb);
320 }
321
322 static gboolean amdvi_iotlb_remove_by_devid(gpointer key, gpointer value,
323                                             gpointer user_data)
324 {
325     AMDVIIOTLBEntry *entry = (AMDVIIOTLBEntry *)value;
326     uint16_t devid = *(uint16_t *)user_data;
327     return entry->devid == devid;
328 }
329
330 static void amdvi_iotlb_remove_page(AMDVIState *s, hwaddr addr,
331                                     uint64_t devid)
332 {
333     uint64_t key = (addr >> AMDVI_PAGE_SHIFT_4K) |
334                    ((uint64_t)(devid) << AMDVI_DEVID_SHIFT);
335     g_hash_table_remove(s->iotlb, &key);
336 }
337
338 static void amdvi_update_iotlb(AMDVIState *s, uint16_t devid,
339                                uint64_t gpa, IOMMUTLBEntry to_cache,
340                                uint16_t domid)
341 {
342     AMDVIIOTLBEntry *entry = g_new(AMDVIIOTLBEntry, 1);
343     uint64_t *key = g_new(uint64_t, 1);
344     uint64_t gfn = gpa >> AMDVI_PAGE_SHIFT_4K;
345
346     /* don't cache erroneous translations */
347     if (to_cache.perm != IOMMU_NONE) {
348         trace_amdvi_cache_update(domid, PCI_BUS_NUM(devid), PCI_SLOT(devid),
349                 PCI_FUNC(devid), gpa, to_cache.translated_addr);
350
351         if (g_hash_table_size(s->iotlb) >= AMDVI_IOTLB_MAX_SIZE) {
352             amdvi_iotlb_reset(s);
353         }
354
355         entry->domid = domid;
356         entry->perms = to_cache.perm;
357         entry->translated_addr = to_cache.translated_addr;
358         entry->page_mask = to_cache.addr_mask;
359         *key = gfn | ((uint64_t)(devid) << AMDVI_DEVID_SHIFT);
360         g_hash_table_replace(s->iotlb, key, entry);
361     }
362 }
363
364 static void amdvi_completion_wait(AMDVIState *s, uint64_t *cmd)
365 {
366     /* pad the last 3 bits */
367     hwaddr addr = cpu_to_le64(extract64(cmd[0], 3, 49)) << 3;
368     uint64_t data = cpu_to_le64(cmd[1]);
369
370     if (extract64(cmd[0], 51, 8)) {
371         amdvi_log_illegalcom_error(s, extract64(cmd[0], 60, 4),
372                                    s->cmdbuf + s->cmdbuf_head);
373     }
374     if (extract64(cmd[0], 0, 1)) {
375         if (dma_memory_write(&address_space_memory, addr, &data,
376             AMDVI_COMPLETION_DATA_SIZE)) {
377             trace_amdvi_completion_wait_fail(addr);
378         }
379     }
380     /* set completion interrupt */
381     if (extract64(cmd[0], 1, 1)) {
382         amdvi_test_mask(s, AMDVI_MMIO_STATUS, AMDVI_MMIO_STATUS_COMP_INT);
383         /* generate interrupt */
384         amdvi_generate_msi_interrupt(s);
385     }
386     trace_amdvi_completion_wait(addr, data);
387 }
388
389 /* log error without aborting since linux seems to be using reserved bits */
390 static void amdvi_inval_devtab_entry(AMDVIState *s, uint64_t *cmd)
391 {
392     uint16_t devid = cpu_to_le16((uint16_t)extract64(cmd[0], 0, 16));
393
394     /* This command should invalidate internal caches of which there isn't */
395     if (extract64(cmd[0], 15, 16) || cmd[1]) {
396         amdvi_log_illegalcom_error(s, extract64(cmd[0], 60, 4),
397                                    s->cmdbuf + s->cmdbuf_head);
398     }
399     trace_amdvi_devtab_inval(PCI_BUS_NUM(devid), PCI_SLOT(devid),
400                              PCI_FUNC(devid));
401 }
402
403 static void amdvi_complete_ppr(AMDVIState *s, uint64_t *cmd)
404 {
405     if (extract64(cmd[0], 15, 16) ||  extract64(cmd[0], 19, 8) ||
406         extract64(cmd[1], 0, 2) || extract64(cmd[1], 3, 29)
407         || extract64(cmd[1], 47, 16)) {
408         amdvi_log_illegalcom_error(s, extract64(cmd[0], 60, 4),
409                                    s->cmdbuf + s->cmdbuf_head);
410     }
411     trace_amdvi_ppr_exec();
412 }
413
414 static void amdvi_inval_all(AMDVIState *s, uint64_t *cmd)
415 {
416     if (extract64(cmd[0], 0, 60) || cmd[1]) {
417         amdvi_log_illegalcom_error(s, extract64(cmd[0], 60, 4),
418                                    s->cmdbuf + s->cmdbuf_head);
419     }
420
421     amdvi_iotlb_reset(s);
422     trace_amdvi_all_inval();
423 }
424
425 static gboolean amdvi_iotlb_remove_by_domid(gpointer key, gpointer value,
426                                             gpointer user_data)
427 {
428     AMDVIIOTLBEntry *entry = (AMDVIIOTLBEntry *)value;
429     uint16_t domid = *(uint16_t *)user_data;
430     return entry->domid == domid;
431 }
432
433 /* we don't have devid - we can't remove pages by address */
434 static void amdvi_inval_pages(AMDVIState *s, uint64_t *cmd)
435 {
436     uint16_t domid = cpu_to_le16((uint16_t)extract64(cmd[0], 32, 16));
437
438     if (extract64(cmd[0], 20, 12) || extract64(cmd[0], 16, 12) ||
439         extract64(cmd[0], 3, 10)) {
440         amdvi_log_illegalcom_error(s, extract64(cmd[0], 60, 4),
441                                    s->cmdbuf + s->cmdbuf_head);
442     }
443
444     g_hash_table_foreach_remove(s->iotlb, amdvi_iotlb_remove_by_domid,
445                                 &domid);
446     trace_amdvi_pages_inval(domid);
447 }
448
449 static void amdvi_prefetch_pages(AMDVIState *s, uint64_t *cmd)
450 {
451     if (extract64(cmd[0], 16, 8) || extract64(cmd[0], 20, 8) ||
452         extract64(cmd[1], 1, 1) || extract64(cmd[1], 3, 1) ||
453         extract64(cmd[1], 5, 7)) {
454         amdvi_log_illegalcom_error(s, extract64(cmd[0], 60, 4),
455                                    s->cmdbuf + s->cmdbuf_head);
456     }
457
458     trace_amdvi_prefetch_pages();
459 }
460
461 static void amdvi_inval_inttable(AMDVIState *s, uint64_t *cmd)
462 {
463     if (extract64(cmd[0], 16, 16) || cmd[1]) {
464         amdvi_log_illegalcom_error(s, extract64(cmd[0], 60, 4),
465                                    s->cmdbuf + s->cmdbuf_head);
466         return;
467     }
468
469     trace_amdvi_intr_inval();
470 }
471
472 /* FIXME: Try to work with the specified size instead of all the pages
473  * when the S bit is on
474  */
475 static void iommu_inval_iotlb(AMDVIState *s, uint64_t *cmd)
476 {
477
478     uint16_t devid = extract64(cmd[0], 0, 16);
479     if (extract64(cmd[1], 1, 1) || extract64(cmd[1], 3, 9)) {
480         amdvi_log_illegalcom_error(s, extract64(cmd[0], 60, 4),
481                                    s->cmdbuf + s->cmdbuf_head);
482         return;
483     }
484
485     if (extract64(cmd[1], 0, 1)) {
486         g_hash_table_foreach_remove(s->iotlb, amdvi_iotlb_remove_by_devid,
487                                     &devid);
488     } else {
489         amdvi_iotlb_remove_page(s, cpu_to_le64(extract64(cmd[1], 12, 52)) << 12,
490                                 cpu_to_le16(extract64(cmd[1], 0, 16)));
491     }
492     trace_amdvi_iotlb_inval();
493 }
494
495 /* not honouring reserved bits is regarded as an illegal command */
496 static void amdvi_cmdbuf_exec(AMDVIState *s)
497 {
498     uint64_t cmd[2];
499
500     if (dma_memory_read(&address_space_memory, s->cmdbuf + s->cmdbuf_head,
501         cmd, AMDVI_COMMAND_SIZE)) {
502         trace_amdvi_command_read_fail(s->cmdbuf, s->cmdbuf_head);
503         amdvi_log_command_error(s, s->cmdbuf + s->cmdbuf_head);
504         return;
505     }
506
507     switch (extract64(cmd[0], 60, 4)) {
508     case AMDVI_CMD_COMPLETION_WAIT:
509         amdvi_completion_wait(s, cmd);
510         break;
511     case AMDVI_CMD_INVAL_DEVTAB_ENTRY:
512         amdvi_inval_devtab_entry(s, cmd);
513         break;
514     case AMDVI_CMD_INVAL_AMDVI_PAGES:
515         amdvi_inval_pages(s, cmd);
516         break;
517     case AMDVI_CMD_INVAL_IOTLB_PAGES:
518         iommu_inval_iotlb(s, cmd);
519         break;
520     case AMDVI_CMD_INVAL_INTR_TABLE:
521         amdvi_inval_inttable(s, cmd);
522         break;
523     case AMDVI_CMD_PREFETCH_AMDVI_PAGES:
524         amdvi_prefetch_pages(s, cmd);
525         break;
526     case AMDVI_CMD_COMPLETE_PPR_REQUEST:
527         amdvi_complete_ppr(s, cmd);
528         break;
529     case AMDVI_CMD_INVAL_AMDVI_ALL:
530         amdvi_inval_all(s, cmd);
531         break;
532     default:
533         trace_amdvi_unhandled_command(extract64(cmd[1], 60, 4));
534         /* log illegal command */
535         amdvi_log_illegalcom_error(s, extract64(cmd[1], 60, 4),
536                                    s->cmdbuf + s->cmdbuf_head);
537     }
538 }
539
540 static void amdvi_cmdbuf_run(AMDVIState *s)
541 {
542     if (!s->cmdbuf_enabled) {
543         trace_amdvi_command_error(amdvi_readq(s, AMDVI_MMIO_CONTROL));
544         return;
545     }
546
547     /* check if there is work to do. */
548     while (s->cmdbuf_head != s->cmdbuf_tail) {
549         trace_amdvi_command_exec(s->cmdbuf_head, s->cmdbuf_tail, s->cmdbuf);
550         amdvi_cmdbuf_exec(s);
551         s->cmdbuf_head += AMDVI_COMMAND_SIZE;
552         amdvi_writeq_raw(s, s->cmdbuf_head, AMDVI_MMIO_COMMAND_HEAD);
553
554         /* wrap head pointer */
555         if (s->cmdbuf_head >= s->cmdbuf_len * AMDVI_COMMAND_SIZE) {
556             s->cmdbuf_head = 0;
557         }
558     }
559 }
560
561 static void amdvi_mmio_trace(hwaddr addr, unsigned size)
562 {
563     uint8_t index = (addr & ~0x2000) / 8;
564
565     if ((addr & 0x2000)) {
566         /* high table */
567         index = index >= AMDVI_MMIO_REGS_HIGH ? AMDVI_MMIO_REGS_HIGH : index;
568         trace_amdvi_mmio_read(amdvi_mmio_high[index], addr, size, addr & ~0x07);
569     } else {
570         index = index >= AMDVI_MMIO_REGS_LOW ? AMDVI_MMIO_REGS_LOW : index;
571         trace_amdvi_mmio_read(amdvi_mmio_low[index], addr, size, addr & ~0x07);
572     }
573 }
574
575 static uint64_t amdvi_mmio_read(void *opaque, hwaddr addr, unsigned size)
576 {
577     AMDVIState *s = opaque;
578
579     uint64_t val = -1;
580     if (addr + size > AMDVI_MMIO_SIZE) {
581         trace_amdvi_mmio_read_invalid(AMDVI_MMIO_SIZE, addr, size);
582         return (uint64_t)-1;
583     }
584
585     if (size == 2) {
586         val = amdvi_readw(s, addr);
587     } else if (size == 4) {
588         val = amdvi_readl(s, addr);
589     } else if (size == 8) {
590         val = amdvi_readq(s, addr);
591     }
592     amdvi_mmio_trace(addr, size);
593
594     return val;
595 }
596
597 static void amdvi_handle_control_write(AMDVIState *s)
598 {
599     unsigned long control = amdvi_readq(s, AMDVI_MMIO_CONTROL);
600     s->enabled = !!(control & AMDVI_MMIO_CONTROL_AMDVIEN);
601
602     s->ats_enabled = !!(control & AMDVI_MMIO_CONTROL_HTTUNEN);
603     s->evtlog_enabled = s->enabled && !!(control &
604                         AMDVI_MMIO_CONTROL_EVENTLOGEN);
605
606     s->evtlog_intr = !!(control & AMDVI_MMIO_CONTROL_EVENTINTEN);
607     s->completion_wait_intr = !!(control & AMDVI_MMIO_CONTROL_COMWAITINTEN);
608     s->cmdbuf_enabled = s->enabled && !!(control &
609                         AMDVI_MMIO_CONTROL_CMDBUFLEN);
610
611     /* update the flags depending on the control register */
612     if (s->cmdbuf_enabled) {
613         amdvi_assign_orq(s, AMDVI_MMIO_STATUS, AMDVI_MMIO_STATUS_CMDBUF_RUN);
614     } else {
615         amdvi_assign_andq(s, AMDVI_MMIO_STATUS, ~AMDVI_MMIO_STATUS_CMDBUF_RUN);
616     }
617     if (s->evtlog_enabled) {
618         amdvi_assign_orq(s, AMDVI_MMIO_STATUS, AMDVI_MMIO_STATUS_EVT_RUN);
619     } else {
620         amdvi_assign_andq(s, AMDVI_MMIO_STATUS, ~AMDVI_MMIO_STATUS_EVT_RUN);
621     }
622
623     trace_amdvi_control_status(control);
624     amdvi_cmdbuf_run(s);
625 }
626
627 static inline void amdvi_handle_devtab_write(AMDVIState *s)
628
629 {
630     uint64_t val = amdvi_readq(s, AMDVI_MMIO_DEVICE_TABLE);
631     s->devtab = (val & AMDVI_MMIO_DEVTAB_BASE_MASK);
632
633     /* set device table length */
634     s->devtab_len = ((val & AMDVI_MMIO_DEVTAB_SIZE_MASK) + 1 *
635                     (AMDVI_MMIO_DEVTAB_SIZE_UNIT /
636                      AMDVI_MMIO_DEVTAB_ENTRY_SIZE));
637 }
638
639 static inline void amdvi_handle_cmdhead_write(AMDVIState *s)
640 {
641     s->cmdbuf_head = amdvi_readq(s, AMDVI_MMIO_COMMAND_HEAD)
642                      & AMDVI_MMIO_CMDBUF_HEAD_MASK;
643     amdvi_cmdbuf_run(s);
644 }
645
646 static inline void amdvi_handle_cmdbase_write(AMDVIState *s)
647 {
648     s->cmdbuf = amdvi_readq(s, AMDVI_MMIO_COMMAND_BASE)
649                 & AMDVI_MMIO_CMDBUF_BASE_MASK;
650     s->cmdbuf_len = 1UL << (amdvi_readq(s, AMDVI_MMIO_CMDBUF_SIZE_BYTE)
651                     & AMDVI_MMIO_CMDBUF_SIZE_MASK);
652     s->cmdbuf_head = s->cmdbuf_tail = 0;
653 }
654
655 static inline void amdvi_handle_cmdtail_write(AMDVIState *s)
656 {
657     s->cmdbuf_tail = amdvi_readq(s, AMDVI_MMIO_COMMAND_TAIL)
658                      & AMDVI_MMIO_CMDBUF_TAIL_MASK;
659     amdvi_cmdbuf_run(s);
660 }
661
662 static inline void amdvi_handle_excllim_write(AMDVIState *s)
663 {
664     uint64_t val = amdvi_readq(s, AMDVI_MMIO_EXCL_LIMIT);
665     s->excl_limit = (val & AMDVI_MMIO_EXCL_LIMIT_MASK) |
666                     AMDVI_MMIO_EXCL_LIMIT_LOW;
667 }
668
669 static inline void amdvi_handle_evtbase_write(AMDVIState *s)
670 {
671     uint64_t val = amdvi_readq(s, AMDVI_MMIO_EVENT_BASE);
672     s->evtlog = val & AMDVI_MMIO_EVTLOG_BASE_MASK;
673     s->evtlog_len = 1UL << (amdvi_readq(s, AMDVI_MMIO_EVTLOG_SIZE_BYTE)
674                     & AMDVI_MMIO_EVTLOG_SIZE_MASK);
675 }
676
677 static inline void amdvi_handle_evttail_write(AMDVIState *s)
678 {
679     uint64_t val = amdvi_readq(s, AMDVI_MMIO_EVENT_TAIL);
680     s->evtlog_tail = val & AMDVI_MMIO_EVTLOG_TAIL_MASK;
681 }
682
683 static inline void amdvi_handle_evthead_write(AMDVIState *s)
684 {
685     uint64_t val = amdvi_readq(s, AMDVI_MMIO_EVENT_HEAD);
686     s->evtlog_head = val & AMDVI_MMIO_EVTLOG_HEAD_MASK;
687 }
688
689 static inline void amdvi_handle_pprbase_write(AMDVIState *s)
690 {
691     uint64_t val = amdvi_readq(s, AMDVI_MMIO_PPR_BASE);
692     s->ppr_log = val & AMDVI_MMIO_PPRLOG_BASE_MASK;
693     s->pprlog_len = 1UL << (amdvi_readq(s, AMDVI_MMIO_PPRLOG_SIZE_BYTE)
694                     & AMDVI_MMIO_PPRLOG_SIZE_MASK);
695 }
696
697 static inline void amdvi_handle_pprhead_write(AMDVIState *s)
698 {
699     uint64_t val = amdvi_readq(s, AMDVI_MMIO_PPR_HEAD);
700     s->pprlog_head = val & AMDVI_MMIO_PPRLOG_HEAD_MASK;
701 }
702
703 static inline void amdvi_handle_pprtail_write(AMDVIState *s)
704 {
705     uint64_t val = amdvi_readq(s, AMDVI_MMIO_PPR_TAIL);
706     s->pprlog_tail = val & AMDVI_MMIO_PPRLOG_TAIL_MASK;
707 }
708
709 /* FIXME: something might go wrong if System Software writes in chunks
710  * of one byte but linux writes in chunks of 4 bytes so currently it
711  * works correctly with linux but will definitely be busted if software
712  * reads/writes 8 bytes
713  */
714 static void amdvi_mmio_reg_write(AMDVIState *s, unsigned size, uint64_t val,
715                                  hwaddr addr)
716 {
717     if (size == 2) {
718         amdvi_writew(s, addr, val);
719     } else if (size == 4) {
720         amdvi_writel(s, addr, val);
721     } else if (size == 8) {
722         amdvi_writeq(s, addr, val);
723     }
724 }
725
726 static void amdvi_mmio_write(void *opaque, hwaddr addr, uint64_t val,
727                              unsigned size)
728 {
729     AMDVIState *s = opaque;
730     unsigned long offset = addr & 0x07;
731
732     if (addr + size > AMDVI_MMIO_SIZE) {
733         trace_amdvi_mmio_write("error: addr outside region: max ",
734                 (uint64_t)AMDVI_MMIO_SIZE, size, val, offset);
735         return;
736     }
737
738     amdvi_mmio_trace(addr, size);
739     switch (addr & ~0x07) {
740     case AMDVI_MMIO_CONTROL:
741         amdvi_mmio_reg_write(s, size, val, addr);
742         amdvi_handle_control_write(s);
743         break;
744     case AMDVI_MMIO_DEVICE_TABLE:
745         amdvi_mmio_reg_write(s, size, val, addr);
746        /*  set device table address
747         *   This also suffers from inability to tell whether software
748         *   is done writing
749         */
750         if (offset || (size == 8)) {
751             amdvi_handle_devtab_write(s);
752         }
753         break;
754     case AMDVI_MMIO_COMMAND_HEAD:
755         amdvi_mmio_reg_write(s, size, val, addr);
756         amdvi_handle_cmdhead_write(s);
757         break;
758     case AMDVI_MMIO_COMMAND_BASE:
759         amdvi_mmio_reg_write(s, size, val, addr);
760         /* FIXME - make sure System Software has finished writing incase
761          * it writes in chucks less than 8 bytes in a robust way.As for
762          * now, this hacks works for the linux driver
763          */
764         if (offset || (size == 8)) {
765             amdvi_handle_cmdbase_write(s);
766         }
767         break;
768     case AMDVI_MMIO_COMMAND_TAIL:
769         amdvi_mmio_reg_write(s, size, val, addr);
770         amdvi_handle_cmdtail_write(s);
771         break;
772     case AMDVI_MMIO_EVENT_BASE:
773         amdvi_mmio_reg_write(s, size, val, addr);
774         amdvi_handle_evtbase_write(s);
775         break;
776     case AMDVI_MMIO_EVENT_HEAD:
777         amdvi_mmio_reg_write(s, size, val, addr);
778         amdvi_handle_evthead_write(s);
779         break;
780     case AMDVI_MMIO_EVENT_TAIL:
781         amdvi_mmio_reg_write(s, size, val, addr);
782         amdvi_handle_evttail_write(s);
783         break;
784     case AMDVI_MMIO_EXCL_LIMIT:
785         amdvi_mmio_reg_write(s, size, val, addr);
786         amdvi_handle_excllim_write(s);
787         break;
788         /* PPR log base - unused for now */
789     case AMDVI_MMIO_PPR_BASE:
790         amdvi_mmio_reg_write(s, size, val, addr);
791         amdvi_handle_pprbase_write(s);
792         break;
793         /* PPR log head - also unused for now */
794     case AMDVI_MMIO_PPR_HEAD:
795         amdvi_mmio_reg_write(s, size, val, addr);
796         amdvi_handle_pprhead_write(s);
797         break;
798         /* PPR log tail - unused for now */
799     case AMDVI_MMIO_PPR_TAIL:
800         amdvi_mmio_reg_write(s, size, val, addr);
801         amdvi_handle_pprtail_write(s);
802         break;
803     }
804 }
805
806 static inline uint64_t amdvi_get_perms(uint64_t entry)
807 {
808     return (entry & (AMDVI_DEV_PERM_READ | AMDVI_DEV_PERM_WRITE)) >>
809            AMDVI_DEV_PERM_SHIFT;
810 }
811
812 /* validate that reserved bits are honoured */
813 static bool amdvi_validate_dte(AMDVIState *s, uint16_t devid,
814                                uint64_t *dte)
815 {
816     if ((dte[0] & AMDVI_DTE_LOWER_QUAD_RESERVED)
817         || (dte[1] & AMDVI_DTE_MIDDLE_QUAD_RESERVED)
818         || (dte[2] & AMDVI_DTE_UPPER_QUAD_RESERVED) || dte[3]) {
819         amdvi_log_illegaldevtab_error(s, devid,
820                                       s->devtab +
821                                       devid * AMDVI_DEVTAB_ENTRY_SIZE, 0);
822         return false;
823     }
824
825     return true;
826 }
827
828 /* get a device table entry given the devid */
829 static bool amdvi_get_dte(AMDVIState *s, int devid, uint64_t *entry)
830 {
831     uint32_t offset = devid * AMDVI_DEVTAB_ENTRY_SIZE;
832
833     if (dma_memory_read(&address_space_memory, s->devtab + offset, entry,
834         AMDVI_DEVTAB_ENTRY_SIZE)) {
835         trace_amdvi_dte_get_fail(s->devtab, offset);
836         /* log error accessing dte */
837         amdvi_log_devtab_error(s, devid, s->devtab + offset, 0);
838         return false;
839     }
840
841     *entry = le64_to_cpu(*entry);
842     if (!amdvi_validate_dte(s, devid, entry)) {
843         trace_amdvi_invalid_dte(entry[0]);
844         return false;
845     }
846
847     return true;
848 }
849
850 /* get pte translation mode */
851 static inline uint8_t get_pte_translation_mode(uint64_t pte)
852 {
853     return (pte >> AMDVI_DEV_MODE_RSHIFT) & AMDVI_DEV_MODE_MASK;
854 }
855
856 static inline uint64_t pte_override_page_mask(uint64_t pte)
857 {
858     uint8_t page_mask = 12;
859     uint64_t addr = (pte & AMDVI_DEV_PT_ROOT_MASK) ^ AMDVI_DEV_PT_ROOT_MASK;
860     /* find the first zero bit */
861     while (addr & 1) {
862         page_mask++;
863         addr = addr >> 1;
864     }
865
866     return ~((1ULL << page_mask) - 1);
867 }
868
869 static inline uint64_t pte_get_page_mask(uint64_t oldlevel)
870 {
871     return ~((1UL << ((oldlevel * 9) + 3)) - 1);
872 }
873
874 static inline uint64_t amdvi_get_pte_entry(AMDVIState *s, uint64_t pte_addr,
875                                           uint16_t devid)
876 {
877     uint64_t pte;
878
879     if (dma_memory_read(&address_space_memory, pte_addr, &pte, sizeof(pte))) {
880         trace_amdvi_get_pte_hwerror(pte_addr);
881         amdvi_log_pagetab_error(s, devid, pte_addr, 0);
882         pte = 0;
883         return pte;
884     }
885
886     pte = le64_to_cpu(pte);
887     return pte;
888 }
889
890 static void amdvi_page_walk(AMDVIAddressSpace *as, uint64_t *dte,
891                             IOMMUTLBEntry *ret, unsigned perms,
892                             hwaddr addr)
893 {
894     unsigned level, present, pte_perms, oldlevel;
895     uint64_t pte = dte[0], pte_addr, page_mask;
896
897     /* make sure the DTE has TV = 1 */
898     if (pte & AMDVI_DEV_TRANSLATION_VALID) {
899         level = get_pte_translation_mode(pte);
900         if (level >= 7) {
901             trace_amdvi_mode_invalid(level, addr);
902             return;
903         }
904         if (level == 0) {
905             goto no_remap;
906         }
907
908         /* we are at the leaf page table or page table encodes a huge page */
909         while (level > 0) {
910             pte_perms = amdvi_get_perms(pte);
911             present = pte & 1;
912             if (!present || perms != (perms & pte_perms)) {
913                 amdvi_page_fault(as->iommu_state, as->devfn, addr, perms);
914                 trace_amdvi_page_fault(addr);
915                 return;
916             }
917
918             /* go to the next lower level */
919             pte_addr = pte & AMDVI_DEV_PT_ROOT_MASK;
920             /* add offset and load pte */
921             pte_addr += ((addr >> (3 + 9 * level)) & 0x1FF) << 3;
922             pte = amdvi_get_pte_entry(as->iommu_state, pte_addr, as->devfn);
923             if (!pte) {
924                 return;
925             }
926             oldlevel = level;
927             level = get_pte_translation_mode(pte);
928             if (level == 0x7) {
929                 break;
930             }
931         }
932
933         if (level == 0x7) {
934             page_mask = pte_override_page_mask(pte);
935         } else {
936             page_mask = pte_get_page_mask(oldlevel);
937         }
938
939         /* get access permissions from pte */
940         ret->iova = addr & page_mask;
941         ret->translated_addr = (pte & AMDVI_DEV_PT_ROOT_MASK) & page_mask;
942         ret->addr_mask = ~page_mask;
943         ret->perm = amdvi_get_perms(pte);
944         return;
945     }
946 no_remap:
947     ret->iova = addr & AMDVI_PAGE_MASK_4K;
948     ret->translated_addr = addr & AMDVI_PAGE_MASK_4K;
949     ret->addr_mask = ~AMDVI_PAGE_MASK_4K;
950     ret->perm = amdvi_get_perms(pte);
951 }
952
953 static void amdvi_do_translate(AMDVIAddressSpace *as, hwaddr addr,
954                                bool is_write, IOMMUTLBEntry *ret)
955 {
956     AMDVIState *s = as->iommu_state;
957     uint16_t devid = PCI_BUILD_BDF(as->bus_num, as->devfn);
958     AMDVIIOTLBEntry *iotlb_entry = amdvi_iotlb_lookup(s, addr, devid);
959     uint64_t entry[4];
960
961     if (iotlb_entry) {
962         trace_amdvi_iotlb_hit(PCI_BUS_NUM(devid), PCI_SLOT(devid),
963                 PCI_FUNC(devid), addr, iotlb_entry->translated_addr);
964         ret->iova = addr & ~iotlb_entry->page_mask;
965         ret->translated_addr = iotlb_entry->translated_addr;
966         ret->addr_mask = iotlb_entry->page_mask;
967         ret->perm = iotlb_entry->perms;
968         return;
969     }
970
971     if (!amdvi_get_dte(s, devid, entry)) {
972         return;
973     }
974
975     /* devices with V = 0 are not translated */
976     if (!(entry[0] & AMDVI_DEV_VALID)) {
977         goto out;
978     }
979
980     amdvi_page_walk(as, entry, ret,
981                     is_write ? AMDVI_PERM_WRITE : AMDVI_PERM_READ, addr);
982
983     amdvi_update_iotlb(s, devid, addr, *ret,
984                        entry[1] & AMDVI_DEV_DOMID_ID_MASK);
985     return;
986
987 out:
988     ret->iova = addr & AMDVI_PAGE_MASK_4K;
989     ret->translated_addr = addr & AMDVI_PAGE_MASK_4K;
990     ret->addr_mask = ~AMDVI_PAGE_MASK_4K;
991     ret->perm = IOMMU_RW;
992 }
993
994 static inline bool amdvi_is_interrupt_addr(hwaddr addr)
995 {
996     return addr >= AMDVI_INT_ADDR_FIRST && addr <= AMDVI_INT_ADDR_LAST;
997 }
998
999 static IOMMUTLBEntry amdvi_translate(IOMMUMemoryRegion *iommu, hwaddr addr,
1000                                      IOMMUAccessFlags flag, int iommu_idx)
1001 {
1002     AMDVIAddressSpace *as = container_of(iommu, AMDVIAddressSpace, iommu);
1003     AMDVIState *s = as->iommu_state;
1004     IOMMUTLBEntry ret = {
1005         .target_as = &address_space_memory,
1006         .iova = addr,
1007         .translated_addr = 0,
1008         .addr_mask = ~(hwaddr)0,
1009         .perm = IOMMU_NONE
1010     };
1011
1012     if (!s->enabled) {
1013         /* AMDVI disabled - corresponds to iommu=off not
1014          * failure to provide any parameter
1015          */
1016         ret.iova = addr & AMDVI_PAGE_MASK_4K;
1017         ret.translated_addr = addr & AMDVI_PAGE_MASK_4K;
1018         ret.addr_mask = ~AMDVI_PAGE_MASK_4K;
1019         ret.perm = IOMMU_RW;
1020         return ret;
1021     } else if (amdvi_is_interrupt_addr(addr)) {
1022         ret.iova = addr & AMDVI_PAGE_MASK_4K;
1023         ret.translated_addr = addr & AMDVI_PAGE_MASK_4K;
1024         ret.addr_mask = ~AMDVI_PAGE_MASK_4K;
1025         ret.perm = IOMMU_WO;
1026         return ret;
1027     }
1028
1029     amdvi_do_translate(as, addr, flag & IOMMU_WO, &ret);
1030     trace_amdvi_translation_result(as->bus_num, PCI_SLOT(as->devfn),
1031             PCI_FUNC(as->devfn), addr, ret.translated_addr);
1032     return ret;
1033 }
1034
1035 /* Interrupt remapping for MSI/MSI-X entry */
1036 static int amdvi_int_remap_msi(AMDVIState *iommu,
1037                                MSIMessage *origin,
1038                                MSIMessage *translated,
1039                                uint16_t sid)
1040 {
1041     assert(origin && translated);
1042
1043     trace_amdvi_ir_remap_msi_req(origin->address, origin->data, sid);
1044
1045     if (!iommu || !X86_IOMMU_DEVICE(iommu)->intr_supported) {
1046         memcpy(translated, origin, sizeof(*origin));
1047         goto out;
1048     }
1049
1050     if (origin->address & AMDVI_MSI_ADDR_HI_MASK) {
1051         trace_amdvi_err("MSI address high 32 bits non-zero when "
1052                         "Interrupt Remapping enabled.");
1053         return -AMDVI_IR_ERR;
1054     }
1055
1056     if ((origin->address & AMDVI_MSI_ADDR_LO_MASK) != APIC_DEFAULT_ADDRESS) {
1057         trace_amdvi_err("MSI is not from IOAPIC.");
1058         return -AMDVI_IR_ERR;
1059     }
1060
1061 out:
1062     trace_amdvi_ir_remap_msi(origin->address, origin->data,
1063                              translated->address, translated->data);
1064     return 0;
1065 }
1066
1067 static int amdvi_int_remap(X86IOMMUState *iommu,
1068                            MSIMessage *origin,
1069                            MSIMessage *translated,
1070                            uint16_t sid)
1071 {
1072     return amdvi_int_remap_msi(AMD_IOMMU_DEVICE(iommu), origin,
1073                                translated, sid);
1074 }
1075
1076 static MemTxResult amdvi_mem_ir_write(void *opaque, hwaddr addr,
1077                                       uint64_t value, unsigned size,
1078                                       MemTxAttrs attrs)
1079 {
1080     int ret;
1081     MSIMessage from = { 0, 0 }, to = { 0, 0 };
1082     uint16_t sid = AMDVI_IOAPIC_SB_DEVID;
1083
1084     from.address = (uint64_t) addr + AMDVI_INT_ADDR_FIRST;
1085     from.data = (uint32_t) value;
1086
1087     trace_amdvi_mem_ir_write_req(addr, value, size);
1088
1089     if (!attrs.unspecified) {
1090         /* We have explicit Source ID */
1091         sid = attrs.requester_id;
1092     }
1093
1094     ret = amdvi_int_remap_msi(opaque, &from, &to, sid);
1095     if (ret < 0) {
1096         /* TODO: log the event using IOMMU log event interface */
1097         error_report_once("failed to remap interrupt from devid 0x%x", sid);
1098         return MEMTX_ERROR;
1099     }
1100
1101     apic_get_class()->send_msi(&to);
1102
1103     trace_amdvi_mem_ir_write(to.address, to.data);
1104     return MEMTX_OK;
1105 }
1106
1107 static MemTxResult amdvi_mem_ir_read(void *opaque, hwaddr addr,
1108                                      uint64_t *data, unsigned size,
1109                                      MemTxAttrs attrs)
1110 {
1111     return MEMTX_OK;
1112 }
1113
1114 static const MemoryRegionOps amdvi_ir_ops = {
1115     .read_with_attrs = amdvi_mem_ir_read,
1116     .write_with_attrs = amdvi_mem_ir_write,
1117     .endianness = DEVICE_LITTLE_ENDIAN,
1118     .impl = {
1119         .min_access_size = 4,
1120         .max_access_size = 4,
1121     },
1122     .valid = {
1123         .min_access_size = 4,
1124         .max_access_size = 4,
1125     }
1126 };
1127
1128 static AddressSpace *amdvi_host_dma_iommu(PCIBus *bus, void *opaque, int devfn)
1129 {
1130     char name[128];
1131     AMDVIState *s = opaque;
1132     AMDVIAddressSpace **iommu_as, *amdvi_dev_as;
1133     int bus_num = pci_bus_num(bus);
1134
1135     iommu_as = s->address_spaces[bus_num];
1136
1137     /* allocate memory during the first run */
1138     if (!iommu_as) {
1139         iommu_as = g_malloc0(sizeof(AMDVIAddressSpace *) * PCI_DEVFN_MAX);
1140         s->address_spaces[bus_num] = iommu_as;
1141     }
1142
1143     /* set up AMD-Vi region */
1144     if (!iommu_as[devfn]) {
1145         snprintf(name, sizeof(name), "amd_iommu_devfn_%d", devfn);
1146
1147         iommu_as[devfn] = g_malloc0(sizeof(AMDVIAddressSpace));
1148         iommu_as[devfn]->bus_num = (uint8_t)bus_num;
1149         iommu_as[devfn]->devfn = (uint8_t)devfn;
1150         iommu_as[devfn]->iommu_state = s;
1151
1152         amdvi_dev_as = iommu_as[devfn];
1153
1154         /*
1155          * Memory region relationships looks like (Address range shows
1156          * only lower 32 bits to make it short in length...):
1157          *
1158          * |-----------------+-------------------+----------|
1159          * | Name            | Address range     | Priority |
1160          * |-----------------+-------------------+----------+
1161          * | amdvi_root      | 00000000-ffffffff |        0 |
1162          * |  amdvi_iommu    | 00000000-ffffffff |        1 |
1163          * |  amdvi_iommu_ir | fee00000-feefffff |       64 |
1164          * |-----------------+-------------------+----------|
1165          */
1166         memory_region_init_iommu(&amdvi_dev_as->iommu,
1167                                  sizeof(amdvi_dev_as->iommu),
1168                                  TYPE_AMD_IOMMU_MEMORY_REGION,
1169                                  OBJECT(s),
1170                                  "amd_iommu", UINT64_MAX);
1171         memory_region_init(&amdvi_dev_as->root, OBJECT(s),
1172                            "amdvi_root", UINT64_MAX);
1173         address_space_init(&amdvi_dev_as->as, &amdvi_dev_as->root, name);
1174         memory_region_init_io(&amdvi_dev_as->iommu_ir, OBJECT(s),
1175                               &amdvi_ir_ops, s, "amd_iommu_ir",
1176                               AMDVI_INT_ADDR_SIZE);
1177         memory_region_add_subregion_overlap(&amdvi_dev_as->root,
1178                                             AMDVI_INT_ADDR_FIRST,
1179                                             &amdvi_dev_as->iommu_ir,
1180                                             64);
1181         memory_region_add_subregion_overlap(&amdvi_dev_as->root, 0,
1182                                             MEMORY_REGION(&amdvi_dev_as->iommu),
1183                                             1);
1184     }
1185     return &iommu_as[devfn]->as;
1186 }
1187
1188 static const MemoryRegionOps mmio_mem_ops = {
1189     .read = amdvi_mmio_read,
1190     .write = amdvi_mmio_write,
1191     .endianness = DEVICE_LITTLE_ENDIAN,
1192     .impl = {
1193         .min_access_size = 1,
1194         .max_access_size = 8,
1195         .unaligned = false,
1196     },
1197     .valid = {
1198         .min_access_size = 1,
1199         .max_access_size = 8,
1200     }
1201 };
1202
1203 static void amdvi_iommu_notify_flag_changed(IOMMUMemoryRegion *iommu,
1204                                             IOMMUNotifierFlag old,
1205                                             IOMMUNotifierFlag new)
1206 {
1207     AMDVIAddressSpace *as = container_of(iommu, AMDVIAddressSpace, iommu);
1208
1209     if (new & IOMMU_NOTIFIER_MAP) {
1210         error_report("device %02x.%02x.%x requires iommu notifier which is not "
1211                      "currently supported", as->bus_num, PCI_SLOT(as->devfn),
1212                      PCI_FUNC(as->devfn));
1213         exit(1);
1214     }
1215 }
1216
1217 static void amdvi_init(AMDVIState *s)
1218 {
1219     amdvi_iotlb_reset(s);
1220
1221     s->devtab_len = 0;
1222     s->cmdbuf_len = 0;
1223     s->cmdbuf_head = 0;
1224     s->cmdbuf_tail = 0;
1225     s->evtlog_head = 0;
1226     s->evtlog_tail = 0;
1227     s->excl_enabled = false;
1228     s->excl_allow = false;
1229     s->mmio_enabled = false;
1230     s->enabled = false;
1231     s->ats_enabled = false;
1232     s->cmdbuf_enabled = false;
1233
1234     /* reset MMIO */
1235     memset(s->mmior, 0, AMDVI_MMIO_SIZE);
1236     amdvi_set_quad(s, AMDVI_MMIO_EXT_FEATURES, AMDVI_EXT_FEATURES,
1237             0xffffffffffffffef, 0);
1238     amdvi_set_quad(s, AMDVI_MMIO_STATUS, 0, 0x98, 0x67);
1239
1240     /* reset device ident */
1241     pci_config_set_vendor_id(s->pci.dev.config, PCI_VENDOR_ID_AMD);
1242     pci_config_set_prog_interface(s->pci.dev.config, 00);
1243     pci_config_set_device_id(s->pci.dev.config, s->devid);
1244     pci_config_set_class(s->pci.dev.config, 0x0806);
1245
1246     /* reset AMDVI specific capabilities, all r/o */
1247     pci_set_long(s->pci.dev.config + s->capab_offset, AMDVI_CAPAB_FEATURES);
1248     pci_set_long(s->pci.dev.config + s->capab_offset + AMDVI_CAPAB_BAR_LOW,
1249                  s->mmio.addr & ~(0xffff0000));
1250     pci_set_long(s->pci.dev.config + s->capab_offset + AMDVI_CAPAB_BAR_HIGH,
1251                 (s->mmio.addr & ~(0xffff)) >> 16);
1252     pci_set_long(s->pci.dev.config + s->capab_offset + AMDVI_CAPAB_RANGE,
1253                  0xff000000);
1254     pci_set_long(s->pci.dev.config + s->capab_offset + AMDVI_CAPAB_MISC, 0);
1255     pci_set_long(s->pci.dev.config + s->capab_offset + AMDVI_CAPAB_MISC,
1256             AMDVI_MAX_PH_ADDR | AMDVI_MAX_GVA_ADDR | AMDVI_MAX_VA_ADDR);
1257 }
1258
1259 static void amdvi_reset(DeviceState *dev)
1260 {
1261     AMDVIState *s = AMD_IOMMU_DEVICE(dev);
1262
1263     msi_reset(&s->pci.dev);
1264     amdvi_init(s);
1265 }
1266
1267 static void amdvi_realize(DeviceState *dev, Error **err)
1268 {
1269     int ret = 0;
1270     AMDVIState *s = AMD_IOMMU_DEVICE(dev);
1271     X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(dev);
1272     MachineState *ms = MACHINE(qdev_get_machine());
1273     PCMachineState *pcms = PC_MACHINE(ms);
1274     PCIBus *bus = pcms->bus;
1275
1276     s->iotlb = g_hash_table_new_full(amdvi_uint64_hash,
1277                                      amdvi_uint64_equal, g_free, g_free);
1278
1279     /* This device should take care of IOMMU PCI properties */
1280     x86_iommu->type = TYPE_AMD;
1281     qdev_set_parent_bus(DEVICE(&s->pci), &bus->qbus);
1282     object_property_set_bool(OBJECT(&s->pci), true, "realized", err);
1283     ret = pci_add_capability(&s->pci.dev, AMDVI_CAPAB_ID_SEC, 0,
1284                                          AMDVI_CAPAB_SIZE, err);
1285     if (ret < 0) {
1286         return;
1287     }
1288     s->capab_offset = ret;
1289
1290     ret = pci_add_capability(&s->pci.dev, PCI_CAP_ID_MSI, 0,
1291                              AMDVI_CAPAB_REG_SIZE, err);
1292     if (ret < 0) {
1293         return;
1294     }
1295     ret = pci_add_capability(&s->pci.dev, PCI_CAP_ID_HT, 0,
1296                              AMDVI_CAPAB_REG_SIZE, err);
1297     if (ret < 0) {
1298         return;
1299     }
1300
1301     /* Pseudo address space under root PCI bus. */
1302     pcms->ioapic_as = amdvi_host_dma_iommu(bus, s, AMDVI_IOAPIC_SB_DEVID);
1303
1304     /* set up MMIO */
1305     memory_region_init_io(&s->mmio, OBJECT(s), &mmio_mem_ops, s, "amdvi-mmio",
1306                           AMDVI_MMIO_SIZE);
1307
1308     sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->mmio);
1309     sysbus_mmio_map(SYS_BUS_DEVICE(s), 0, AMDVI_BASE_ADDR);
1310     pci_setup_iommu(bus, amdvi_host_dma_iommu, s);
1311     s->devid = object_property_get_int(OBJECT(&s->pci), "addr", err);
1312     msi_init(&s->pci.dev, 0, 1, true, false, err);
1313     amdvi_init(s);
1314 }
1315
1316 static const VMStateDescription vmstate_amdvi = {
1317     .name = "amd-iommu",
1318     .unmigratable = 1
1319 };
1320
1321 static void amdvi_instance_init(Object *klass)
1322 {
1323     AMDVIState *s = AMD_IOMMU_DEVICE(klass);
1324
1325     object_initialize(&s->pci, sizeof(s->pci), TYPE_AMD_IOMMU_PCI);
1326 }
1327
1328 static void amdvi_class_init(ObjectClass *klass, void* data)
1329 {
1330     DeviceClass *dc = DEVICE_CLASS(klass);
1331     X86IOMMUClass *dc_class = X86_IOMMU_CLASS(klass);
1332
1333     dc->reset = amdvi_reset;
1334     dc->vmsd = &vmstate_amdvi;
1335     dc->hotpluggable = false;
1336     dc_class->realize = amdvi_realize;
1337     dc_class->int_remap = amdvi_int_remap;
1338     /* Supported by the pc-q35-* machine types */
1339     dc->user_creatable = true;
1340 }
1341
1342 static const TypeInfo amdvi = {
1343     .name = TYPE_AMD_IOMMU_DEVICE,
1344     .parent = TYPE_X86_IOMMU_DEVICE,
1345     .instance_size = sizeof(AMDVIState),
1346     .instance_init = amdvi_instance_init,
1347     .class_init = amdvi_class_init
1348 };
1349
1350 static const TypeInfo amdviPCI = {
1351     .name = "AMDVI-PCI",
1352     .parent = TYPE_PCI_DEVICE,
1353     .instance_size = sizeof(AMDVIPCIState),
1354     .interfaces = (InterfaceInfo[]) {
1355         { INTERFACE_CONVENTIONAL_PCI_DEVICE },
1356         { },
1357     },
1358 };
1359
1360 static void amdvi_iommu_memory_region_class_init(ObjectClass *klass, void *data)
1361 {
1362     IOMMUMemoryRegionClass *imrc = IOMMU_MEMORY_REGION_CLASS(klass);
1363
1364     imrc->translate = amdvi_translate;
1365     imrc->notify_flag_changed = amdvi_iommu_notify_flag_changed;
1366 }
1367
1368 static const TypeInfo amdvi_iommu_memory_region_info = {
1369     .parent = TYPE_IOMMU_MEMORY_REGION,
1370     .name = TYPE_AMD_IOMMU_MEMORY_REGION,
1371     .class_init = amdvi_iommu_memory_region_class_init,
1372 };
1373
1374 static void amdviPCI_register_types(void)
1375 {
1376     type_register_static(&amdviPCI);
1377     type_register_static(&amdvi);
1378     type_register_static(&amdvi_iommu_memory_region_info);
1379 }
1380
1381 type_init(amdviPCI_register_types);
This page took 0.099741 seconds and 4 git commands to generate.