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