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