]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - arch/x86/kernel/amd_iommu.c
49f2c8533e12a08daf8f848e67f5e26a1cb3114a
[karo-tx-linux.git] / arch / x86 / kernel / amd_iommu.c
1 /*
2  * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
3  * Author: Joerg Roedel <joerg.roedel@amd.com>
4  *         Leo Duran <leo.duran@amd.com>
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 as published
8  * by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
18  */
19
20 #include <linux/pci.h>
21 #include <linux/gfp.h>
22 #include <linux/bitops.h>
23 #include <linux/debugfs.h>
24 #include <linux/scatterlist.h>
25 #include <linux/iommu-helper.h>
26 #ifdef CONFIG_IOMMU_API
27 #include <linux/iommu.h>
28 #endif
29 #include <asm/proto.h>
30 #include <asm/iommu.h>
31 #include <asm/gart.h>
32 #include <asm/amd_iommu_types.h>
33 #include <asm/amd_iommu.h>
34
35 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
36
37 #define EXIT_LOOP_COUNT 10000000
38
39 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
40
41 /* A list of preallocated protection domains */
42 static LIST_HEAD(iommu_pd_list);
43 static DEFINE_SPINLOCK(iommu_pd_list_lock);
44
45 #ifdef CONFIG_IOMMU_API
46 static struct iommu_ops amd_iommu_ops;
47 #endif
48
49 /*
50  * general struct to manage commands send to an IOMMU
51  */
52 struct iommu_cmd {
53         u32 data[4];
54 };
55
56 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
57                              struct unity_map_entry *e);
58 static struct dma_ops_domain *find_protection_domain(u16 devid);
59
60
61 #ifdef CONFIG_AMD_IOMMU_STATS
62
63 /*
64  * Initialization code for statistics collection
65  */
66
67 DECLARE_STATS_COUNTER(compl_wait);
68 DECLARE_STATS_COUNTER(cnt_map_single);
69 DECLARE_STATS_COUNTER(cnt_unmap_single);
70 DECLARE_STATS_COUNTER(cnt_map_sg);
71 DECLARE_STATS_COUNTER(cnt_unmap_sg);
72
73 static struct dentry *stats_dir;
74 static struct dentry *de_isolate;
75 static struct dentry *de_fflush;
76
77 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
78 {
79         if (stats_dir == NULL)
80                 return;
81
82         cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
83                                        &cnt->value);
84 }
85
86 static void amd_iommu_stats_init(void)
87 {
88         stats_dir = debugfs_create_dir("amd-iommu", NULL);
89         if (stats_dir == NULL)
90                 return;
91
92         de_isolate = debugfs_create_bool("isolation", 0444, stats_dir,
93                                          (u32 *)&amd_iommu_isolate);
94
95         de_fflush  = debugfs_create_bool("fullflush", 0444, stats_dir,
96                                          (u32 *)&amd_iommu_unmap_flush);
97
98         amd_iommu_stats_add(&compl_wait);
99         amd_iommu_stats_add(&cnt_map_single);
100         amd_iommu_stats_add(&cnt_unmap_single);
101         amd_iommu_stats_add(&cnt_map_sg);
102         amd_iommu_stats_add(&cnt_unmap_sg);
103 }
104
105 #endif
106
107 /* returns !0 if the IOMMU is caching non-present entries in its TLB */
108 static int iommu_has_npcache(struct amd_iommu *iommu)
109 {
110         return iommu->cap & (1UL << IOMMU_CAP_NPCACHE);
111 }
112
113 /****************************************************************************
114  *
115  * Interrupt handling functions
116  *
117  ****************************************************************************/
118
119 static void iommu_print_event(void *__evt)
120 {
121         u32 *event = __evt;
122         int type  = (event[1] >> EVENT_TYPE_SHIFT)  & EVENT_TYPE_MASK;
123         int devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
124         int domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
125         int flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
126         u64 address = (u64)(((u64)event[3]) << 32) | event[2];
127
128         printk(KERN_ERR "AMD IOMMU: Event logged [");
129
130         switch (type) {
131         case EVENT_TYPE_ILL_DEV:
132                 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
133                        "address=0x%016llx flags=0x%04x]\n",
134                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
135                        address, flags);
136                 break;
137         case EVENT_TYPE_IO_FAULT:
138                 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
139                        "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
140                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
141                        domid, address, flags);
142                 break;
143         case EVENT_TYPE_DEV_TAB_ERR:
144                 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
145                        "address=0x%016llx flags=0x%04x]\n",
146                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
147                        address, flags);
148                 break;
149         case EVENT_TYPE_PAGE_TAB_ERR:
150                 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
151                        "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
152                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
153                        domid, address, flags);
154                 break;
155         case EVENT_TYPE_ILL_CMD:
156                 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
157                 break;
158         case EVENT_TYPE_CMD_HARD_ERR:
159                 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
160                        "flags=0x%04x]\n", address, flags);
161                 break;
162         case EVENT_TYPE_IOTLB_INV_TO:
163                 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
164                        "address=0x%016llx]\n",
165                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
166                        address);
167                 break;
168         case EVENT_TYPE_INV_DEV_REQ:
169                 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
170                        "address=0x%016llx flags=0x%04x]\n",
171                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
172                        address, flags);
173                 break;
174         default:
175                 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
176         }
177 }
178
179 static void iommu_poll_events(struct amd_iommu *iommu)
180 {
181         u32 head, tail;
182         unsigned long flags;
183
184         spin_lock_irqsave(&iommu->lock, flags);
185
186         head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
187         tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
188
189         while (head != tail) {
190                 iommu_print_event(iommu->evt_buf + head);
191                 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
192         }
193
194         writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
195
196         spin_unlock_irqrestore(&iommu->lock, flags);
197 }
198
199 irqreturn_t amd_iommu_int_handler(int irq, void *data)
200 {
201         struct amd_iommu *iommu;
202
203         list_for_each_entry(iommu, &amd_iommu_list, list)
204                 iommu_poll_events(iommu);
205
206         return IRQ_HANDLED;
207 }
208
209 /****************************************************************************
210  *
211  * IOMMU command queuing functions
212  *
213  ****************************************************************************/
214
215 /*
216  * Writes the command to the IOMMUs command buffer and informs the
217  * hardware about the new command. Must be called with iommu->lock held.
218  */
219 static int __iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
220 {
221         u32 tail, head;
222         u8 *target;
223
224         tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
225         target = iommu->cmd_buf + tail;
226         memcpy_toio(target, cmd, sizeof(*cmd));
227         tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
228         head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
229         if (tail == head)
230                 return -ENOMEM;
231         writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
232
233         return 0;
234 }
235
236 /*
237  * General queuing function for commands. Takes iommu->lock and calls
238  * __iommu_queue_command().
239  */
240 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
241 {
242         unsigned long flags;
243         int ret;
244
245         spin_lock_irqsave(&iommu->lock, flags);
246         ret = __iommu_queue_command(iommu, cmd);
247         if (!ret)
248                 iommu->need_sync = true;
249         spin_unlock_irqrestore(&iommu->lock, flags);
250
251         return ret;
252 }
253
254 /*
255  * This function waits until an IOMMU has completed a completion
256  * wait command
257  */
258 static void __iommu_wait_for_completion(struct amd_iommu *iommu)
259 {
260         int ready = 0;
261         unsigned status = 0;
262         unsigned long i = 0;
263
264         INC_STATS_COUNTER(compl_wait);
265
266         while (!ready && (i < EXIT_LOOP_COUNT)) {
267                 ++i;
268                 /* wait for the bit to become one */
269                 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
270                 ready = status & MMIO_STATUS_COM_WAIT_INT_MASK;
271         }
272
273         /* set bit back to zero */
274         status &= ~MMIO_STATUS_COM_WAIT_INT_MASK;
275         writel(status, iommu->mmio_base + MMIO_STATUS_OFFSET);
276
277         if (unlikely(i == EXIT_LOOP_COUNT))
278                 panic("AMD IOMMU: Completion wait loop failed\n");
279 }
280
281 /*
282  * This function queues a completion wait command into the command
283  * buffer of an IOMMU
284  */
285 static int __iommu_completion_wait(struct amd_iommu *iommu)
286 {
287         struct iommu_cmd cmd;
288
289          memset(&cmd, 0, sizeof(cmd));
290          cmd.data[0] = CMD_COMPL_WAIT_INT_MASK;
291          CMD_SET_TYPE(&cmd, CMD_COMPL_WAIT);
292
293          return __iommu_queue_command(iommu, &cmd);
294 }
295
296 /*
297  * This function is called whenever we need to ensure that the IOMMU has
298  * completed execution of all commands we sent. It sends a
299  * COMPLETION_WAIT command and waits for it to finish. The IOMMU informs
300  * us about that by writing a value to a physical address we pass with
301  * the command.
302  */
303 static int iommu_completion_wait(struct amd_iommu *iommu)
304 {
305         int ret = 0;
306         unsigned long flags;
307
308         spin_lock_irqsave(&iommu->lock, flags);
309
310         if (!iommu->need_sync)
311                 goto out;
312
313         ret = __iommu_completion_wait(iommu);
314
315         iommu->need_sync = false;
316
317         if (ret)
318                 goto out;
319
320         __iommu_wait_for_completion(iommu);
321
322 out:
323         spin_unlock_irqrestore(&iommu->lock, flags);
324
325         return 0;
326 }
327
328 /*
329  * Command send function for invalidating a device table entry
330  */
331 static int iommu_queue_inv_dev_entry(struct amd_iommu *iommu, u16 devid)
332 {
333         struct iommu_cmd cmd;
334         int ret;
335
336         BUG_ON(iommu == NULL);
337
338         memset(&cmd, 0, sizeof(cmd));
339         CMD_SET_TYPE(&cmd, CMD_INV_DEV_ENTRY);
340         cmd.data[0] = devid;
341
342         ret = iommu_queue_command(iommu, &cmd);
343
344         return ret;
345 }
346
347 static void __iommu_build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
348                                           u16 domid, int pde, int s)
349 {
350         memset(cmd, 0, sizeof(*cmd));
351         address &= PAGE_MASK;
352         CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
353         cmd->data[1] |= domid;
354         cmd->data[2] = lower_32_bits(address);
355         cmd->data[3] = upper_32_bits(address);
356         if (s) /* size bit - we flush more than one 4kb page */
357                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
358         if (pde) /* PDE bit - we wan't flush everything not only the PTEs */
359                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
360 }
361
362 /*
363  * Generic command send function for invalidaing TLB entries
364  */
365 static int iommu_queue_inv_iommu_pages(struct amd_iommu *iommu,
366                 u64 address, u16 domid, int pde, int s)
367 {
368         struct iommu_cmd cmd;
369         int ret;
370
371         __iommu_build_inv_iommu_pages(&cmd, address, domid, pde, s);
372
373         ret = iommu_queue_command(iommu, &cmd);
374
375         return ret;
376 }
377
378 /*
379  * TLB invalidation function which is called from the mapping functions.
380  * It invalidates a single PTE if the range to flush is within a single
381  * page. Otherwise it flushes the whole TLB of the IOMMU.
382  */
383 static int iommu_flush_pages(struct amd_iommu *iommu, u16 domid,
384                 u64 address, size_t size)
385 {
386         int s = 0;
387         unsigned pages = iommu_num_pages(address, size, PAGE_SIZE);
388
389         address &= PAGE_MASK;
390
391         if (pages > 1) {
392                 /*
393                  * If we have to flush more than one page, flush all
394                  * TLB entries for this domain
395                  */
396                 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
397                 s = 1;
398         }
399
400         iommu_queue_inv_iommu_pages(iommu, address, domid, 0, s);
401
402         return 0;
403 }
404
405 /* Flush the whole IO/TLB for a given protection domain */
406 static void iommu_flush_tlb(struct amd_iommu *iommu, u16 domid)
407 {
408         u64 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
409
410         iommu_queue_inv_iommu_pages(iommu, address, domid, 0, 1);
411 }
412
413 #ifdef CONFIG_IOMMU_API
414 /*
415  * This function is used to flush the IO/TLB for a given protection domain
416  * on every IOMMU in the system
417  */
418 static void iommu_flush_domain(u16 domid)
419 {
420         unsigned long flags;
421         struct amd_iommu *iommu;
422         struct iommu_cmd cmd;
423
424         __iommu_build_inv_iommu_pages(&cmd, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
425                                       domid, 1, 1);
426
427         list_for_each_entry(iommu, &amd_iommu_list, list) {
428                 spin_lock_irqsave(&iommu->lock, flags);
429                 __iommu_queue_command(iommu, &cmd);
430                 __iommu_completion_wait(iommu);
431                 __iommu_wait_for_completion(iommu);
432                 spin_unlock_irqrestore(&iommu->lock, flags);
433         }
434 }
435 #endif
436
437 /****************************************************************************
438  *
439  * The functions below are used the create the page table mappings for
440  * unity mapped regions.
441  *
442  ****************************************************************************/
443
444 /*
445  * Generic mapping functions. It maps a physical address into a DMA
446  * address space. It allocates the page table pages if necessary.
447  * In the future it can be extended to a generic mapping function
448  * supporting all features of AMD IOMMU page tables like level skipping
449  * and full 64 bit address spaces.
450  */
451 static int iommu_map_page(struct protection_domain *dom,
452                           unsigned long bus_addr,
453                           unsigned long phys_addr,
454                           int prot)
455 {
456         u64 __pte, *pte, *page;
457
458         bus_addr  = PAGE_ALIGN(bus_addr);
459         phys_addr = PAGE_ALIGN(phys_addr);
460
461         /* only support 512GB address spaces for now */
462         if (bus_addr > IOMMU_MAP_SIZE_L3 || !(prot & IOMMU_PROT_MASK))
463                 return -EINVAL;
464
465         pte = &dom->pt_root[IOMMU_PTE_L2_INDEX(bus_addr)];
466
467         if (!IOMMU_PTE_PRESENT(*pte)) {
468                 page = (u64 *)get_zeroed_page(GFP_KERNEL);
469                 if (!page)
470                         return -ENOMEM;
471                 *pte = IOMMU_L2_PDE(virt_to_phys(page));
472         }
473
474         pte = IOMMU_PTE_PAGE(*pte);
475         pte = &pte[IOMMU_PTE_L1_INDEX(bus_addr)];
476
477         if (!IOMMU_PTE_PRESENT(*pte)) {
478                 page = (u64 *)get_zeroed_page(GFP_KERNEL);
479                 if (!page)
480                         return -ENOMEM;
481                 *pte = IOMMU_L1_PDE(virt_to_phys(page));
482         }
483
484         pte = IOMMU_PTE_PAGE(*pte);
485         pte = &pte[IOMMU_PTE_L0_INDEX(bus_addr)];
486
487         if (IOMMU_PTE_PRESENT(*pte))
488                 return -EBUSY;
489
490         __pte = phys_addr | IOMMU_PTE_P;
491         if (prot & IOMMU_PROT_IR)
492                 __pte |= IOMMU_PTE_IR;
493         if (prot & IOMMU_PROT_IW)
494                 __pte |= IOMMU_PTE_IW;
495
496         *pte = __pte;
497
498         return 0;
499 }
500
501 #ifdef CONFIG_IOMMU_API
502 static void iommu_unmap_page(struct protection_domain *dom,
503                              unsigned long bus_addr)
504 {
505         u64 *pte;
506
507         pte = &dom->pt_root[IOMMU_PTE_L2_INDEX(bus_addr)];
508
509         if (!IOMMU_PTE_PRESENT(*pte))
510                 return;
511
512         pte = IOMMU_PTE_PAGE(*pte);
513         pte = &pte[IOMMU_PTE_L1_INDEX(bus_addr)];
514
515         if (!IOMMU_PTE_PRESENT(*pte))
516                 return;
517
518         pte = IOMMU_PTE_PAGE(*pte);
519         pte = &pte[IOMMU_PTE_L1_INDEX(bus_addr)];
520
521         *pte = 0;
522 }
523 #endif
524
525 /*
526  * This function checks if a specific unity mapping entry is needed for
527  * this specific IOMMU.
528  */
529 static int iommu_for_unity_map(struct amd_iommu *iommu,
530                                struct unity_map_entry *entry)
531 {
532         u16 bdf, i;
533
534         for (i = entry->devid_start; i <= entry->devid_end; ++i) {
535                 bdf = amd_iommu_alias_table[i];
536                 if (amd_iommu_rlookup_table[bdf] == iommu)
537                         return 1;
538         }
539
540         return 0;
541 }
542
543 /*
544  * Init the unity mappings for a specific IOMMU in the system
545  *
546  * Basically iterates over all unity mapping entries and applies them to
547  * the default domain DMA of that IOMMU if necessary.
548  */
549 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
550 {
551         struct unity_map_entry *entry;
552         int ret;
553
554         list_for_each_entry(entry, &amd_iommu_unity_map, list) {
555                 if (!iommu_for_unity_map(iommu, entry))
556                         continue;
557                 ret = dma_ops_unity_map(iommu->default_dom, entry);
558                 if (ret)
559                         return ret;
560         }
561
562         return 0;
563 }
564
565 /*
566  * This function actually applies the mapping to the page table of the
567  * dma_ops domain.
568  */
569 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
570                              struct unity_map_entry *e)
571 {
572         u64 addr;
573         int ret;
574
575         for (addr = e->address_start; addr < e->address_end;
576              addr += PAGE_SIZE) {
577                 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot);
578                 if (ret)
579                         return ret;
580                 /*
581                  * if unity mapping is in aperture range mark the page
582                  * as allocated in the aperture
583                  */
584                 if (addr < dma_dom->aperture_size)
585                         __set_bit(addr >> PAGE_SHIFT, dma_dom->bitmap);
586         }
587
588         return 0;
589 }
590
591 /*
592  * Inits the unity mappings required for a specific device
593  */
594 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
595                                           u16 devid)
596 {
597         struct unity_map_entry *e;
598         int ret;
599
600         list_for_each_entry(e, &amd_iommu_unity_map, list) {
601                 if (!(devid >= e->devid_start && devid <= e->devid_end))
602                         continue;
603                 ret = dma_ops_unity_map(dma_dom, e);
604                 if (ret)
605                         return ret;
606         }
607
608         return 0;
609 }
610
611 /****************************************************************************
612  *
613  * The next functions belong to the address allocator for the dma_ops
614  * interface functions. They work like the allocators in the other IOMMU
615  * drivers. Its basically a bitmap which marks the allocated pages in
616  * the aperture. Maybe it could be enhanced in the future to a more
617  * efficient allocator.
618  *
619  ****************************************************************************/
620
621 /*
622  * The address allocator core function.
623  *
624  * called with domain->lock held
625  */
626 static unsigned long dma_ops_alloc_addresses(struct device *dev,
627                                              struct dma_ops_domain *dom,
628                                              unsigned int pages,
629                                              unsigned long align_mask,
630                                              u64 dma_mask)
631 {
632         unsigned long limit;
633         unsigned long address;
634         unsigned long boundary_size;
635
636         boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
637                         PAGE_SIZE) >> PAGE_SHIFT;
638         limit = iommu_device_max_index(dom->aperture_size >> PAGE_SHIFT, 0,
639                                        dma_mask >> PAGE_SHIFT);
640
641         if (dom->next_bit >= limit) {
642                 dom->next_bit = 0;
643                 dom->need_flush = true;
644         }
645
646         address = iommu_area_alloc(dom->bitmap, limit, dom->next_bit, pages,
647                                    0 , boundary_size, align_mask);
648         if (address == -1) {
649                 address = iommu_area_alloc(dom->bitmap, limit, 0, pages,
650                                 0, boundary_size, align_mask);
651                 dom->need_flush = true;
652         }
653
654         if (likely(address != -1)) {
655                 dom->next_bit = address + pages;
656                 address <<= PAGE_SHIFT;
657         } else
658                 address = bad_dma_address;
659
660         WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
661
662         return address;
663 }
664
665 /*
666  * The address free function.
667  *
668  * called with domain->lock held
669  */
670 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
671                                    unsigned long address,
672                                    unsigned int pages)
673 {
674         address >>= PAGE_SHIFT;
675         iommu_area_free(dom->bitmap, address, pages);
676
677         if (address >= dom->next_bit)
678                 dom->need_flush = true;
679 }
680
681 /****************************************************************************
682  *
683  * The next functions belong to the domain allocation. A domain is
684  * allocated for every IOMMU as the default domain. If device isolation
685  * is enabled, every device get its own domain. The most important thing
686  * about domains is the page table mapping the DMA address space they
687  * contain.
688  *
689  ****************************************************************************/
690
691 static u16 domain_id_alloc(void)
692 {
693         unsigned long flags;
694         int id;
695
696         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
697         id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
698         BUG_ON(id == 0);
699         if (id > 0 && id < MAX_DOMAIN_ID)
700                 __set_bit(id, amd_iommu_pd_alloc_bitmap);
701         else
702                 id = 0;
703         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
704
705         return id;
706 }
707
708 #ifdef CONFIG_IOMMU_API
709 static void domain_id_free(int id)
710 {
711         unsigned long flags;
712
713         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
714         if (id > 0 && id < MAX_DOMAIN_ID)
715                 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
716         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
717 }
718 #endif
719
720 /*
721  * Used to reserve address ranges in the aperture (e.g. for exclusion
722  * ranges.
723  */
724 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
725                                       unsigned long start_page,
726                                       unsigned int pages)
727 {
728         unsigned int last_page = dom->aperture_size >> PAGE_SHIFT;
729
730         if (start_page + pages > last_page)
731                 pages = last_page - start_page;
732
733         iommu_area_reserve(dom->bitmap, start_page, pages);
734 }
735
736 static void free_pagetable(struct protection_domain *domain)
737 {
738         int i, j;
739         u64 *p1, *p2, *p3;
740
741         p1 = domain->pt_root;
742
743         if (!p1)
744                 return;
745
746         for (i = 0; i < 512; ++i) {
747                 if (!IOMMU_PTE_PRESENT(p1[i]))
748                         continue;
749
750                 p2 = IOMMU_PTE_PAGE(p1[i]);
751                 for (j = 0; j < 512; ++j) {
752                         if (!IOMMU_PTE_PRESENT(p2[j]))
753                                 continue;
754                         p3 = IOMMU_PTE_PAGE(p2[j]);
755                         free_page((unsigned long)p3);
756                 }
757
758                 free_page((unsigned long)p2);
759         }
760
761         free_page((unsigned long)p1);
762
763         domain->pt_root = NULL;
764 }
765
766 /*
767  * Free a domain, only used if something went wrong in the
768  * allocation path and we need to free an already allocated page table
769  */
770 static void dma_ops_domain_free(struct dma_ops_domain *dom)
771 {
772         if (!dom)
773                 return;
774
775         free_pagetable(&dom->domain);
776
777         kfree(dom->pte_pages);
778
779         kfree(dom->bitmap);
780
781         kfree(dom);
782 }
783
784 /*
785  * Allocates a new protection domain usable for the dma_ops functions.
786  * It also intializes the page table and the address allocator data
787  * structures required for the dma_ops interface
788  */
789 static struct dma_ops_domain *dma_ops_domain_alloc(struct amd_iommu *iommu,
790                                                    unsigned order)
791 {
792         struct dma_ops_domain *dma_dom;
793         unsigned i, num_pte_pages;
794         u64 *l2_pde;
795         u64 address;
796
797         /*
798          * Currently the DMA aperture must be between 32 MB and 1GB in size
799          */
800         if ((order < 25) || (order > 30))
801                 return NULL;
802
803         dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
804         if (!dma_dom)
805                 return NULL;
806
807         spin_lock_init(&dma_dom->domain.lock);
808
809         dma_dom->domain.id = domain_id_alloc();
810         if (dma_dom->domain.id == 0)
811                 goto free_dma_dom;
812         dma_dom->domain.mode = PAGE_MODE_3_LEVEL;
813         dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
814         dma_dom->domain.flags = PD_DMA_OPS_MASK;
815         dma_dom->domain.priv = dma_dom;
816         if (!dma_dom->domain.pt_root)
817                 goto free_dma_dom;
818         dma_dom->aperture_size = (1ULL << order);
819         dma_dom->bitmap = kzalloc(dma_dom->aperture_size / (PAGE_SIZE * 8),
820                                   GFP_KERNEL);
821         if (!dma_dom->bitmap)
822                 goto free_dma_dom;
823         /*
824          * mark the first page as allocated so we never return 0 as
825          * a valid dma-address. So we can use 0 as error value
826          */
827         dma_dom->bitmap[0] = 1;
828         dma_dom->next_bit = 0;
829
830         dma_dom->need_flush = false;
831         dma_dom->target_dev = 0xffff;
832
833         /* Intialize the exclusion range if necessary */
834         if (iommu->exclusion_start &&
835             iommu->exclusion_start < dma_dom->aperture_size) {
836                 unsigned long startpage = iommu->exclusion_start >> PAGE_SHIFT;
837                 int pages = iommu_num_pages(iommu->exclusion_start,
838                                             iommu->exclusion_length,
839                                             PAGE_SIZE);
840                 dma_ops_reserve_addresses(dma_dom, startpage, pages);
841         }
842
843         /*
844          * At the last step, build the page tables so we don't need to
845          * allocate page table pages in the dma_ops mapping/unmapping
846          * path.
847          */
848         num_pte_pages = dma_dom->aperture_size / (PAGE_SIZE * 512);
849         dma_dom->pte_pages = kzalloc(num_pte_pages * sizeof(void *),
850                         GFP_KERNEL);
851         if (!dma_dom->pte_pages)
852                 goto free_dma_dom;
853
854         l2_pde = (u64 *)get_zeroed_page(GFP_KERNEL);
855         if (l2_pde == NULL)
856                 goto free_dma_dom;
857
858         dma_dom->domain.pt_root[0] = IOMMU_L2_PDE(virt_to_phys(l2_pde));
859
860         for (i = 0; i < num_pte_pages; ++i) {
861                 dma_dom->pte_pages[i] = (u64 *)get_zeroed_page(GFP_KERNEL);
862                 if (!dma_dom->pte_pages[i])
863                         goto free_dma_dom;
864                 address = virt_to_phys(dma_dom->pte_pages[i]);
865                 l2_pde[i] = IOMMU_L1_PDE(address);
866         }
867
868         return dma_dom;
869
870 free_dma_dom:
871         dma_ops_domain_free(dma_dom);
872
873         return NULL;
874 }
875
876 /*
877  * little helper function to check whether a given protection domain is a
878  * dma_ops domain
879  */
880 static bool dma_ops_domain(struct protection_domain *domain)
881 {
882         return domain->flags & PD_DMA_OPS_MASK;
883 }
884
885 /*
886  * Find out the protection domain structure for a given PCI device. This
887  * will give us the pointer to the page table root for example.
888  */
889 static struct protection_domain *domain_for_device(u16 devid)
890 {
891         struct protection_domain *dom;
892         unsigned long flags;
893
894         read_lock_irqsave(&amd_iommu_devtable_lock, flags);
895         dom = amd_iommu_pd_table[devid];
896         read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
897
898         return dom;
899 }
900
901 /*
902  * If a device is not yet associated with a domain, this function does
903  * assigns it visible for the hardware
904  */
905 static void attach_device(struct amd_iommu *iommu,
906                           struct protection_domain *domain,
907                           u16 devid)
908 {
909         unsigned long flags;
910         u64 pte_root = virt_to_phys(domain->pt_root);
911
912         domain->dev_cnt += 1;
913
914         pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
915                     << DEV_ENTRY_MODE_SHIFT;
916         pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
917
918         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
919         amd_iommu_dev_table[devid].data[0] = lower_32_bits(pte_root);
920         amd_iommu_dev_table[devid].data[1] = upper_32_bits(pte_root);
921         amd_iommu_dev_table[devid].data[2] = domain->id;
922
923         amd_iommu_pd_table[devid] = domain;
924         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
925
926         iommu_queue_inv_dev_entry(iommu, devid);
927 }
928
929 /*
930  * Removes a device from a protection domain (unlocked)
931  */
932 static void __detach_device(struct protection_domain *domain, u16 devid)
933 {
934
935         /* lock domain */
936         spin_lock(&domain->lock);
937
938         /* remove domain from the lookup table */
939         amd_iommu_pd_table[devid] = NULL;
940
941         /* remove entry from the device table seen by the hardware */
942         amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
943         amd_iommu_dev_table[devid].data[1] = 0;
944         amd_iommu_dev_table[devid].data[2] = 0;
945
946         /* decrease reference counter */
947         domain->dev_cnt -= 1;
948
949         /* ready */
950         spin_unlock(&domain->lock);
951 }
952
953 /*
954  * Removes a device from a protection domain (with devtable_lock held)
955  */
956 static void detach_device(struct protection_domain *domain, u16 devid)
957 {
958         unsigned long flags;
959
960         /* lock device table */
961         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
962         __detach_device(domain, devid);
963         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
964 }
965
966 static int device_change_notifier(struct notifier_block *nb,
967                                   unsigned long action, void *data)
968 {
969         struct device *dev = data;
970         struct pci_dev *pdev = to_pci_dev(dev);
971         u16 devid = calc_devid(pdev->bus->number, pdev->devfn);
972         struct protection_domain *domain;
973         struct dma_ops_domain *dma_domain;
974         struct amd_iommu *iommu;
975         int order = amd_iommu_aperture_order;
976         unsigned long flags;
977
978         if (devid > amd_iommu_last_bdf)
979                 goto out;
980
981         devid = amd_iommu_alias_table[devid];
982
983         iommu = amd_iommu_rlookup_table[devid];
984         if (iommu == NULL)
985                 goto out;
986
987         domain = domain_for_device(devid);
988
989         if (domain && !dma_ops_domain(domain))
990                 WARN_ONCE(1, "AMD IOMMU WARNING: device %s already bound "
991                           "to a non-dma-ops domain\n", dev_name(dev));
992
993         switch (action) {
994         case BUS_NOTIFY_BOUND_DRIVER:
995                 if (domain)
996                         goto out;
997                 dma_domain = find_protection_domain(devid);
998                 if (!dma_domain)
999                         dma_domain = iommu->default_dom;
1000                 attach_device(iommu, &dma_domain->domain, devid);
1001                 printk(KERN_INFO "AMD IOMMU: Using protection domain %d for "
1002                        "device %s\n", dma_domain->domain.id, dev_name(dev));
1003                 break;
1004         case BUS_NOTIFY_UNBIND_DRIVER:
1005                 if (!domain)
1006                         goto out;
1007                 detach_device(domain, devid);
1008                 break;
1009         case BUS_NOTIFY_ADD_DEVICE:
1010                 /* allocate a protection domain if a device is added */
1011                 dma_domain = find_protection_domain(devid);
1012                 if (dma_domain)
1013                         goto out;
1014                 dma_domain = dma_ops_domain_alloc(iommu, order);
1015                 if (!dma_domain)
1016                         goto out;
1017                 dma_domain->target_dev = devid;
1018
1019                 spin_lock_irqsave(&iommu_pd_list_lock, flags);
1020                 list_add_tail(&dma_domain->list, &iommu_pd_list);
1021                 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
1022
1023                 break;
1024         default:
1025                 goto out;
1026         }
1027
1028         iommu_queue_inv_dev_entry(iommu, devid);
1029         iommu_completion_wait(iommu);
1030
1031 out:
1032         return 0;
1033 }
1034
1035 struct notifier_block device_nb = {
1036         .notifier_call = device_change_notifier,
1037 };
1038
1039 /*****************************************************************************
1040  *
1041  * The next functions belong to the dma_ops mapping/unmapping code.
1042  *
1043  *****************************************************************************/
1044
1045 /*
1046  * This function checks if the driver got a valid device from the caller to
1047  * avoid dereferencing invalid pointers.
1048  */
1049 static bool check_device(struct device *dev)
1050 {
1051         if (!dev || !dev->dma_mask)
1052                 return false;
1053
1054         return true;
1055 }
1056
1057 /*
1058  * In this function the list of preallocated protection domains is traversed to
1059  * find the domain for a specific device
1060  */
1061 static struct dma_ops_domain *find_protection_domain(u16 devid)
1062 {
1063         struct dma_ops_domain *entry, *ret = NULL;
1064         unsigned long flags;
1065
1066         if (list_empty(&iommu_pd_list))
1067                 return NULL;
1068
1069         spin_lock_irqsave(&iommu_pd_list_lock, flags);
1070
1071         list_for_each_entry(entry, &iommu_pd_list, list) {
1072                 if (entry->target_dev == devid) {
1073                         ret = entry;
1074                         break;
1075                 }
1076         }
1077
1078         spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
1079
1080         return ret;
1081 }
1082
1083 /*
1084  * In the dma_ops path we only have the struct device. This function
1085  * finds the corresponding IOMMU, the protection domain and the
1086  * requestor id for a given device.
1087  * If the device is not yet associated with a domain this is also done
1088  * in this function.
1089  */
1090 static int get_device_resources(struct device *dev,
1091                                 struct amd_iommu **iommu,
1092                                 struct protection_domain **domain,
1093                                 u16 *bdf)
1094 {
1095         struct dma_ops_domain *dma_dom;
1096         struct pci_dev *pcidev;
1097         u16 _bdf;
1098
1099         *iommu = NULL;
1100         *domain = NULL;
1101         *bdf = 0xffff;
1102
1103         if (dev->bus != &pci_bus_type)
1104                 return 0;
1105
1106         pcidev = to_pci_dev(dev);
1107         _bdf = calc_devid(pcidev->bus->number, pcidev->devfn);
1108
1109         /* device not translated by any IOMMU in the system? */
1110         if (_bdf > amd_iommu_last_bdf)
1111                 return 0;
1112
1113         *bdf = amd_iommu_alias_table[_bdf];
1114
1115         *iommu = amd_iommu_rlookup_table[*bdf];
1116         if (*iommu == NULL)
1117                 return 0;
1118         *domain = domain_for_device(*bdf);
1119         if (*domain == NULL) {
1120                 dma_dom = find_protection_domain(*bdf);
1121                 if (!dma_dom)
1122                         dma_dom = (*iommu)->default_dom;
1123                 *domain = &dma_dom->domain;
1124                 attach_device(*iommu, *domain, *bdf);
1125                 printk(KERN_INFO "AMD IOMMU: Using protection domain %d for "
1126                                 "device %s\n", (*domain)->id, dev_name(dev));
1127         }
1128
1129         if (domain_for_device(_bdf) == NULL)
1130                 attach_device(*iommu, *domain, _bdf);
1131
1132         return 1;
1133 }
1134
1135 /*
1136  * This is the generic map function. It maps one 4kb page at paddr to
1137  * the given address in the DMA address space for the domain.
1138  */
1139 static dma_addr_t dma_ops_domain_map(struct amd_iommu *iommu,
1140                                      struct dma_ops_domain *dom,
1141                                      unsigned long address,
1142                                      phys_addr_t paddr,
1143                                      int direction)
1144 {
1145         u64 *pte, __pte;
1146
1147         WARN_ON(address > dom->aperture_size);
1148
1149         paddr &= PAGE_MASK;
1150
1151         pte  = dom->pte_pages[IOMMU_PTE_L1_INDEX(address)];
1152         pte += IOMMU_PTE_L0_INDEX(address);
1153
1154         __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
1155
1156         if (direction == DMA_TO_DEVICE)
1157                 __pte |= IOMMU_PTE_IR;
1158         else if (direction == DMA_FROM_DEVICE)
1159                 __pte |= IOMMU_PTE_IW;
1160         else if (direction == DMA_BIDIRECTIONAL)
1161                 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
1162
1163         WARN_ON(*pte);
1164
1165         *pte = __pte;
1166
1167         return (dma_addr_t)address;
1168 }
1169
1170 /*
1171  * The generic unmapping function for on page in the DMA address space.
1172  */
1173 static void dma_ops_domain_unmap(struct amd_iommu *iommu,
1174                                  struct dma_ops_domain *dom,
1175                                  unsigned long address)
1176 {
1177         u64 *pte;
1178
1179         if (address >= dom->aperture_size)
1180                 return;
1181
1182         WARN_ON(address & ~PAGE_MASK || address >= dom->aperture_size);
1183
1184         pte  = dom->pte_pages[IOMMU_PTE_L1_INDEX(address)];
1185         pte += IOMMU_PTE_L0_INDEX(address);
1186
1187         WARN_ON(!*pte);
1188
1189         *pte = 0ULL;
1190 }
1191
1192 /*
1193  * This function contains common code for mapping of a physically
1194  * contiguous memory region into DMA address space. It is used by all
1195  * mapping functions provided with this IOMMU driver.
1196  * Must be called with the domain lock held.
1197  */
1198 static dma_addr_t __map_single(struct device *dev,
1199                                struct amd_iommu *iommu,
1200                                struct dma_ops_domain *dma_dom,
1201                                phys_addr_t paddr,
1202                                size_t size,
1203                                int dir,
1204                                bool align,
1205                                u64 dma_mask)
1206 {
1207         dma_addr_t offset = paddr & ~PAGE_MASK;
1208         dma_addr_t address, start;
1209         unsigned int pages;
1210         unsigned long align_mask = 0;
1211         int i;
1212
1213         pages = iommu_num_pages(paddr, size, PAGE_SIZE);
1214         paddr &= PAGE_MASK;
1215
1216         if (align)
1217                 align_mask = (1UL << get_order(size)) - 1;
1218
1219         address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
1220                                           dma_mask);
1221         if (unlikely(address == bad_dma_address))
1222                 goto out;
1223
1224         start = address;
1225         for (i = 0; i < pages; ++i) {
1226                 dma_ops_domain_map(iommu, dma_dom, start, paddr, dir);
1227                 paddr += PAGE_SIZE;
1228                 start += PAGE_SIZE;
1229         }
1230         address += offset;
1231
1232         if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
1233                 iommu_flush_tlb(iommu, dma_dom->domain.id);
1234                 dma_dom->need_flush = false;
1235         } else if (unlikely(iommu_has_npcache(iommu)))
1236                 iommu_flush_pages(iommu, dma_dom->domain.id, address, size);
1237
1238 out:
1239         return address;
1240 }
1241
1242 /*
1243  * Does the reverse of the __map_single function. Must be called with
1244  * the domain lock held too
1245  */
1246 static void __unmap_single(struct amd_iommu *iommu,
1247                            struct dma_ops_domain *dma_dom,
1248                            dma_addr_t dma_addr,
1249                            size_t size,
1250                            int dir)
1251 {
1252         dma_addr_t i, start;
1253         unsigned int pages;
1254
1255         if ((dma_addr == bad_dma_address) ||
1256             (dma_addr + size > dma_dom->aperture_size))
1257                 return;
1258
1259         pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
1260         dma_addr &= PAGE_MASK;
1261         start = dma_addr;
1262
1263         for (i = 0; i < pages; ++i) {
1264                 dma_ops_domain_unmap(iommu, dma_dom, start);
1265                 start += PAGE_SIZE;
1266         }
1267
1268         dma_ops_free_addresses(dma_dom, dma_addr, pages);
1269
1270         if (amd_iommu_unmap_flush || dma_dom->need_flush) {
1271                 iommu_flush_pages(iommu, dma_dom->domain.id, dma_addr, size);
1272                 dma_dom->need_flush = false;
1273         }
1274 }
1275
1276 /*
1277  * The exported map_single function for dma_ops.
1278  */
1279 static dma_addr_t map_single(struct device *dev, phys_addr_t paddr,
1280                              size_t size, int dir)
1281 {
1282         unsigned long flags;
1283         struct amd_iommu *iommu;
1284         struct protection_domain *domain;
1285         u16 devid;
1286         dma_addr_t addr;
1287         u64 dma_mask;
1288
1289         INC_STATS_COUNTER(cnt_map_single);
1290
1291         if (!check_device(dev))
1292                 return bad_dma_address;
1293
1294         dma_mask = *dev->dma_mask;
1295
1296         get_device_resources(dev, &iommu, &domain, &devid);
1297
1298         if (iommu == NULL || domain == NULL)
1299                 /* device not handled by any AMD IOMMU */
1300                 return (dma_addr_t)paddr;
1301
1302         if (!dma_ops_domain(domain))
1303                 return bad_dma_address;
1304
1305         spin_lock_irqsave(&domain->lock, flags);
1306         addr = __map_single(dev, iommu, domain->priv, paddr, size, dir, false,
1307                             dma_mask);
1308         if (addr == bad_dma_address)
1309                 goto out;
1310
1311         iommu_completion_wait(iommu);
1312
1313 out:
1314         spin_unlock_irqrestore(&domain->lock, flags);
1315
1316         return addr;
1317 }
1318
1319 /*
1320  * The exported unmap_single function for dma_ops.
1321  */
1322 static void unmap_single(struct device *dev, dma_addr_t dma_addr,
1323                          size_t size, int dir)
1324 {
1325         unsigned long flags;
1326         struct amd_iommu *iommu;
1327         struct protection_domain *domain;
1328         u16 devid;
1329
1330         INC_STATS_COUNTER(cnt_unmap_single);
1331
1332         if (!check_device(dev) ||
1333             !get_device_resources(dev, &iommu, &domain, &devid))
1334                 /* device not handled by any AMD IOMMU */
1335                 return;
1336
1337         if (!dma_ops_domain(domain))
1338                 return;
1339
1340         spin_lock_irqsave(&domain->lock, flags);
1341
1342         __unmap_single(iommu, domain->priv, dma_addr, size, dir);
1343
1344         iommu_completion_wait(iommu);
1345
1346         spin_unlock_irqrestore(&domain->lock, flags);
1347 }
1348
1349 /*
1350  * This is a special map_sg function which is used if we should map a
1351  * device which is not handled by an AMD IOMMU in the system.
1352  */
1353 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
1354                            int nelems, int dir)
1355 {
1356         struct scatterlist *s;
1357         int i;
1358
1359         for_each_sg(sglist, s, nelems, i) {
1360                 s->dma_address = (dma_addr_t)sg_phys(s);
1361                 s->dma_length  = s->length;
1362         }
1363
1364         return nelems;
1365 }
1366
1367 /*
1368  * The exported map_sg function for dma_ops (handles scatter-gather
1369  * lists).
1370  */
1371 static int map_sg(struct device *dev, struct scatterlist *sglist,
1372                   int nelems, int dir)
1373 {
1374         unsigned long flags;
1375         struct amd_iommu *iommu;
1376         struct protection_domain *domain;
1377         u16 devid;
1378         int i;
1379         struct scatterlist *s;
1380         phys_addr_t paddr;
1381         int mapped_elems = 0;
1382         u64 dma_mask;
1383
1384         INC_STATS_COUNTER(cnt_map_sg);
1385
1386         if (!check_device(dev))
1387                 return 0;
1388
1389         dma_mask = *dev->dma_mask;
1390
1391         get_device_resources(dev, &iommu, &domain, &devid);
1392
1393         if (!iommu || !domain)
1394                 return map_sg_no_iommu(dev, sglist, nelems, dir);
1395
1396         if (!dma_ops_domain(domain))
1397                 return 0;
1398
1399         spin_lock_irqsave(&domain->lock, flags);
1400
1401         for_each_sg(sglist, s, nelems, i) {
1402                 paddr = sg_phys(s);
1403
1404                 s->dma_address = __map_single(dev, iommu, domain->priv,
1405                                               paddr, s->length, dir, false,
1406                                               dma_mask);
1407
1408                 if (s->dma_address) {
1409                         s->dma_length = s->length;
1410                         mapped_elems++;
1411                 } else
1412                         goto unmap;
1413         }
1414
1415         iommu_completion_wait(iommu);
1416
1417 out:
1418         spin_unlock_irqrestore(&domain->lock, flags);
1419
1420         return mapped_elems;
1421 unmap:
1422         for_each_sg(sglist, s, mapped_elems, i) {
1423                 if (s->dma_address)
1424                         __unmap_single(iommu, domain->priv, s->dma_address,
1425                                        s->dma_length, dir);
1426                 s->dma_address = s->dma_length = 0;
1427         }
1428
1429         mapped_elems = 0;
1430
1431         goto out;
1432 }
1433
1434 /*
1435  * The exported map_sg function for dma_ops (handles scatter-gather
1436  * lists).
1437  */
1438 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
1439                      int nelems, int dir)
1440 {
1441         unsigned long flags;
1442         struct amd_iommu *iommu;
1443         struct protection_domain *domain;
1444         struct scatterlist *s;
1445         u16 devid;
1446         int i;
1447
1448         INC_STATS_COUNTER(cnt_unmap_sg);
1449
1450         if (!check_device(dev) ||
1451             !get_device_resources(dev, &iommu, &domain, &devid))
1452                 return;
1453
1454         if (!dma_ops_domain(domain))
1455                 return;
1456
1457         spin_lock_irqsave(&domain->lock, flags);
1458
1459         for_each_sg(sglist, s, nelems, i) {
1460                 __unmap_single(iommu, domain->priv, s->dma_address,
1461                                s->dma_length, dir);
1462                 s->dma_address = s->dma_length = 0;
1463         }
1464
1465         iommu_completion_wait(iommu);
1466
1467         spin_unlock_irqrestore(&domain->lock, flags);
1468 }
1469
1470 /*
1471  * The exported alloc_coherent function for dma_ops.
1472  */
1473 static void *alloc_coherent(struct device *dev, size_t size,
1474                             dma_addr_t *dma_addr, gfp_t flag)
1475 {
1476         unsigned long flags;
1477         void *virt_addr;
1478         struct amd_iommu *iommu;
1479         struct protection_domain *domain;
1480         u16 devid;
1481         phys_addr_t paddr;
1482         u64 dma_mask = dev->coherent_dma_mask;
1483
1484         if (!check_device(dev))
1485                 return NULL;
1486
1487         if (!get_device_resources(dev, &iommu, &domain, &devid))
1488                 flag &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
1489
1490         flag |= __GFP_ZERO;
1491         virt_addr = (void *)__get_free_pages(flag, get_order(size));
1492         if (!virt_addr)
1493                 return 0;
1494
1495         paddr = virt_to_phys(virt_addr);
1496
1497         if (!iommu || !domain) {
1498                 *dma_addr = (dma_addr_t)paddr;
1499                 return virt_addr;
1500         }
1501
1502         if (!dma_ops_domain(domain))
1503                 goto out_free;
1504
1505         if (!dma_mask)
1506                 dma_mask = *dev->dma_mask;
1507
1508         spin_lock_irqsave(&domain->lock, flags);
1509
1510         *dma_addr = __map_single(dev, iommu, domain->priv, paddr,
1511                                  size, DMA_BIDIRECTIONAL, true, dma_mask);
1512
1513         if (*dma_addr == bad_dma_address)
1514                 goto out_free;
1515
1516         iommu_completion_wait(iommu);
1517
1518         spin_unlock_irqrestore(&domain->lock, flags);
1519
1520         return virt_addr;
1521
1522 out_free:
1523
1524         free_pages((unsigned long)virt_addr, get_order(size));
1525
1526         return NULL;
1527 }
1528
1529 /*
1530  * The exported free_coherent function for dma_ops.
1531  */
1532 static void free_coherent(struct device *dev, size_t size,
1533                           void *virt_addr, dma_addr_t dma_addr)
1534 {
1535         unsigned long flags;
1536         struct amd_iommu *iommu;
1537         struct protection_domain *domain;
1538         u16 devid;
1539
1540         if (!check_device(dev))
1541                 return;
1542
1543         get_device_resources(dev, &iommu, &domain, &devid);
1544
1545         if (!iommu || !domain)
1546                 goto free_mem;
1547
1548         if (!dma_ops_domain(domain))
1549                 goto free_mem;
1550
1551         spin_lock_irqsave(&domain->lock, flags);
1552
1553         __unmap_single(iommu, domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
1554
1555         iommu_completion_wait(iommu);
1556
1557         spin_unlock_irqrestore(&domain->lock, flags);
1558
1559 free_mem:
1560         free_pages((unsigned long)virt_addr, get_order(size));
1561 }
1562
1563 /*
1564  * This function is called by the DMA layer to find out if we can handle a
1565  * particular device. It is part of the dma_ops.
1566  */
1567 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
1568 {
1569         u16 bdf;
1570         struct pci_dev *pcidev;
1571
1572         /* No device or no PCI device */
1573         if (!dev || dev->bus != &pci_bus_type)
1574                 return 0;
1575
1576         pcidev = to_pci_dev(dev);
1577
1578         bdf = calc_devid(pcidev->bus->number, pcidev->devfn);
1579
1580         /* Out of our scope? */
1581         if (bdf > amd_iommu_last_bdf)
1582                 return 0;
1583
1584         return 1;
1585 }
1586
1587 /*
1588  * The function for pre-allocating protection domains.
1589  *
1590  * If the driver core informs the DMA layer if a driver grabs a device
1591  * we don't need to preallocate the protection domains anymore.
1592  * For now we have to.
1593  */
1594 void prealloc_protection_domains(void)
1595 {
1596         struct pci_dev *dev = NULL;
1597         struct dma_ops_domain *dma_dom;
1598         struct amd_iommu *iommu;
1599         int order = amd_iommu_aperture_order;
1600         u16 devid;
1601
1602         while ((dev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, dev)) != NULL) {
1603                 devid = calc_devid(dev->bus->number, dev->devfn);
1604                 if (devid > amd_iommu_last_bdf)
1605                         continue;
1606                 devid = amd_iommu_alias_table[devid];
1607                 if (domain_for_device(devid))
1608                         continue;
1609                 iommu = amd_iommu_rlookup_table[devid];
1610                 if (!iommu)
1611                         continue;
1612                 dma_dom = dma_ops_domain_alloc(iommu, order);
1613                 if (!dma_dom)
1614                         continue;
1615                 init_unity_mappings_for_device(dma_dom, devid);
1616                 dma_dom->target_dev = devid;
1617
1618                 list_add_tail(&dma_dom->list, &iommu_pd_list);
1619         }
1620 }
1621
1622 static struct dma_mapping_ops amd_iommu_dma_ops = {
1623         .alloc_coherent = alloc_coherent,
1624         .free_coherent = free_coherent,
1625         .map_single = map_single,
1626         .unmap_single = unmap_single,
1627         .map_sg = map_sg,
1628         .unmap_sg = unmap_sg,
1629         .dma_supported = amd_iommu_dma_supported,
1630 };
1631
1632 /*
1633  * The function which clues the AMD IOMMU driver into dma_ops.
1634  */
1635 int __init amd_iommu_init_dma_ops(void)
1636 {
1637         struct amd_iommu *iommu;
1638         int order = amd_iommu_aperture_order;
1639         int ret;
1640
1641         /*
1642          * first allocate a default protection domain for every IOMMU we
1643          * found in the system. Devices not assigned to any other
1644          * protection domain will be assigned to the default one.
1645          */
1646         list_for_each_entry(iommu, &amd_iommu_list, list) {
1647                 iommu->default_dom = dma_ops_domain_alloc(iommu, order);
1648                 if (iommu->default_dom == NULL)
1649                         return -ENOMEM;
1650                 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
1651                 ret = iommu_init_unity_mappings(iommu);
1652                 if (ret)
1653                         goto free_domains;
1654         }
1655
1656         /*
1657          * If device isolation is enabled, pre-allocate the protection
1658          * domains for each device.
1659          */
1660         if (amd_iommu_isolate)
1661                 prealloc_protection_domains();
1662
1663         iommu_detected = 1;
1664         force_iommu = 1;
1665         bad_dma_address = 0;
1666 #ifdef CONFIG_GART_IOMMU
1667         gart_iommu_aperture_disabled = 1;
1668         gart_iommu_aperture = 0;
1669 #endif
1670
1671         /* Make the driver finally visible to the drivers */
1672         dma_ops = &amd_iommu_dma_ops;
1673
1674 #ifdef CONFIG_IOMMU_API
1675         register_iommu(&amd_iommu_ops);
1676 #endif
1677
1678         bus_register_notifier(&pci_bus_type, &device_nb);
1679
1680         amd_iommu_stats_init();
1681
1682         return 0;
1683
1684 free_domains:
1685
1686         list_for_each_entry(iommu, &amd_iommu_list, list) {
1687                 if (iommu->default_dom)
1688                         dma_ops_domain_free(iommu->default_dom);
1689         }
1690
1691         return ret;
1692 }
1693
1694 /*****************************************************************************
1695  *
1696  * The following functions belong to the exported interface of AMD IOMMU
1697  *
1698  * This interface allows access to lower level functions of the IOMMU
1699  * like protection domain handling and assignement of devices to domains
1700  * which is not possible with the dma_ops interface.
1701  *
1702  *****************************************************************************/
1703
1704 #ifdef CONFIG_IOMMU_API
1705
1706 static void cleanup_domain(struct protection_domain *domain)
1707 {
1708         unsigned long flags;
1709         u16 devid;
1710
1711         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1712
1713         for (devid = 0; devid <= amd_iommu_last_bdf; ++devid)
1714                 if (amd_iommu_pd_table[devid] == domain)
1715                         __detach_device(domain, devid);
1716
1717         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1718 }
1719
1720 static int amd_iommu_domain_init(struct iommu_domain *dom)
1721 {
1722         struct protection_domain *domain;
1723
1724         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
1725         if (!domain)
1726                 return -ENOMEM;
1727
1728         spin_lock_init(&domain->lock);
1729         domain->mode = PAGE_MODE_3_LEVEL;
1730         domain->id = domain_id_alloc();
1731         if (!domain->id)
1732                 goto out_free;
1733         domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1734         if (!domain->pt_root)
1735                 goto out_free;
1736
1737         dom->priv = domain;
1738
1739         return 0;
1740
1741 out_free:
1742         kfree(domain);
1743
1744         return -ENOMEM;
1745 }
1746
1747 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
1748 {
1749         struct protection_domain *domain = dom->priv;
1750
1751         if (!domain)
1752                 return;
1753
1754         if (domain->dev_cnt > 0)
1755                 cleanup_domain(domain);
1756
1757         BUG_ON(domain->dev_cnt != 0);
1758
1759         free_pagetable(domain);
1760
1761         domain_id_free(domain->id);
1762
1763         kfree(domain);
1764
1765         dom->priv = NULL;
1766 }
1767
1768 static void amd_iommu_detach_device(struct iommu_domain *dom,
1769                                     struct device *dev)
1770 {
1771         struct protection_domain *domain = dom->priv;
1772         struct amd_iommu *iommu;
1773         struct pci_dev *pdev;
1774         u16 devid;
1775
1776         if (dev->bus != &pci_bus_type)
1777                 return;
1778
1779         pdev = to_pci_dev(dev);
1780
1781         devid = calc_devid(pdev->bus->number, pdev->devfn);
1782
1783         if (devid > 0)
1784                 detach_device(domain, devid);
1785
1786         iommu = amd_iommu_rlookup_table[devid];
1787         if (!iommu)
1788                 return;
1789
1790         iommu_queue_inv_dev_entry(iommu, devid);
1791         iommu_completion_wait(iommu);
1792 }
1793
1794 static int amd_iommu_attach_device(struct iommu_domain *dom,
1795                                    struct device *dev)
1796 {
1797         struct protection_domain *domain = dom->priv;
1798         struct protection_domain *old_domain;
1799         struct amd_iommu *iommu;
1800         struct pci_dev *pdev;
1801         u16 devid;
1802
1803         if (dev->bus != &pci_bus_type)
1804                 return -EINVAL;
1805
1806         pdev = to_pci_dev(dev);
1807
1808         devid = calc_devid(pdev->bus->number, pdev->devfn);
1809
1810         if (devid >= amd_iommu_last_bdf ||
1811                         devid != amd_iommu_alias_table[devid])
1812                 return -EINVAL;
1813
1814         iommu = amd_iommu_rlookup_table[devid];
1815         if (!iommu)
1816                 return -EINVAL;
1817
1818         old_domain = domain_for_device(devid);
1819         if (old_domain)
1820                 return -EBUSY;
1821
1822         attach_device(iommu, domain, devid);
1823
1824         iommu_completion_wait(iommu);
1825
1826         return 0;
1827 }
1828
1829 static int amd_iommu_map_range(struct iommu_domain *dom,
1830                                unsigned long iova, phys_addr_t paddr,
1831                                size_t size, int iommu_prot)
1832 {
1833         struct protection_domain *domain = dom->priv;
1834         unsigned long i,  npages = iommu_num_pages(paddr, size, PAGE_SIZE);
1835         int prot = 0;
1836         int ret;
1837
1838         if (iommu_prot & IOMMU_READ)
1839                 prot |= IOMMU_PROT_IR;
1840         if (iommu_prot & IOMMU_WRITE)
1841                 prot |= IOMMU_PROT_IW;
1842
1843         iova  &= PAGE_MASK;
1844         paddr &= PAGE_MASK;
1845
1846         for (i = 0; i < npages; ++i) {
1847                 ret = iommu_map_page(domain, iova, paddr, prot);
1848                 if (ret)
1849                         return ret;
1850
1851                 iova  += PAGE_SIZE;
1852                 paddr += PAGE_SIZE;
1853         }
1854
1855         return 0;
1856 }
1857
1858 static void amd_iommu_unmap_range(struct iommu_domain *dom,
1859                                   unsigned long iova, size_t size)
1860 {
1861
1862         struct protection_domain *domain = dom->priv;
1863         unsigned long i,  npages = iommu_num_pages(iova, size, PAGE_SIZE);
1864
1865         iova  &= PAGE_MASK;
1866
1867         for (i = 0; i < npages; ++i) {
1868                 iommu_unmap_page(domain, iova);
1869                 iova  += PAGE_SIZE;
1870         }
1871
1872         iommu_flush_domain(domain->id);
1873 }
1874
1875 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
1876                                           unsigned long iova)
1877 {
1878         struct protection_domain *domain = dom->priv;
1879         unsigned long offset = iova & ~PAGE_MASK;
1880         phys_addr_t paddr;
1881         u64 *pte;
1882
1883         pte = &domain->pt_root[IOMMU_PTE_L2_INDEX(iova)];
1884
1885         if (!IOMMU_PTE_PRESENT(*pte))
1886                 return 0;
1887
1888         pte = IOMMU_PTE_PAGE(*pte);
1889         pte = &pte[IOMMU_PTE_L1_INDEX(iova)];
1890
1891         if (!IOMMU_PTE_PRESENT(*pte))
1892                 return 0;
1893
1894         pte = IOMMU_PTE_PAGE(*pte);
1895         pte = &pte[IOMMU_PTE_L0_INDEX(iova)];
1896
1897         if (!IOMMU_PTE_PRESENT(*pte))
1898                 return 0;
1899
1900         paddr  = *pte & IOMMU_PAGE_MASK;
1901         paddr |= offset;
1902
1903         return paddr;
1904 }
1905
1906 static struct iommu_ops amd_iommu_ops = {
1907         .domain_init = amd_iommu_domain_init,
1908         .domain_destroy = amd_iommu_domain_destroy,
1909         .attach_dev = amd_iommu_attach_device,
1910         .detach_dev = amd_iommu_detach_device,
1911         .map = amd_iommu_map_range,
1912         .unmap = amd_iommu_unmap_range,
1913         .iova_to_phys = amd_iommu_iova_to_phys,
1914 };
1915
1916 #endif