]> rtime.felk.cvut.cz Git - linux-imx.git/blob - arch/x86/kernel/amd_iommu.c
iommu/amd: Don't use MSI address range for DMA addresses
[linux-imx.git] / arch / x86 / kernel / amd_iommu.c
1 /*
2  * Copyright (C) 2007-2009 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/bitmap.h>
22 #include <linux/slab.h>
23 #include <linux/debugfs.h>
24 #include <linux/scatterlist.h>
25 #include <linux/dma-mapping.h>
26 #include <linux/iommu-helper.h>
27 #include <linux/iommu.h>
28 #include <asm/msidef.h>
29 #include <asm/proto.h>
30 #include <asm/iommu.h>
31 #include <asm/gart.h>
32 #include <asm/amd_iommu_proto.h>
33 #include <asm/amd_iommu_types.h>
34 #include <asm/amd_iommu.h>
35
36 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
37
38 #define EXIT_LOOP_COUNT 10000000
39
40 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
41
42 /* A list of preallocated protection domains */
43 static LIST_HEAD(iommu_pd_list);
44 static DEFINE_SPINLOCK(iommu_pd_list_lock);
45
46 /*
47  * Domain for untranslated devices - only allocated
48  * if iommu=pt passed on kernel cmd line.
49  */
50 static struct protection_domain *pt_domain;
51
52 static struct iommu_ops amd_iommu_ops;
53
54 /*
55  * general struct to manage commands send to an IOMMU
56  */
57 struct iommu_cmd {
58         u32 data[4];
59 };
60
61 static void reset_iommu_command_buffer(struct amd_iommu *iommu);
62 static void update_domain(struct protection_domain *domain);
63
64 /****************************************************************************
65  *
66  * Helper functions
67  *
68  ****************************************************************************/
69
70 static inline u16 get_device_id(struct device *dev)
71 {
72         struct pci_dev *pdev = to_pci_dev(dev);
73
74         return calc_devid(pdev->bus->number, pdev->devfn);
75 }
76
77 static struct iommu_dev_data *get_dev_data(struct device *dev)
78 {
79         return dev->archdata.iommu;
80 }
81
82 /*
83  * In this function the list of preallocated protection domains is traversed to
84  * find the domain for a specific device
85  */
86 static struct dma_ops_domain *find_protection_domain(u16 devid)
87 {
88         struct dma_ops_domain *entry, *ret = NULL;
89         unsigned long flags;
90         u16 alias = amd_iommu_alias_table[devid];
91
92         if (list_empty(&iommu_pd_list))
93                 return NULL;
94
95         spin_lock_irqsave(&iommu_pd_list_lock, flags);
96
97         list_for_each_entry(entry, &iommu_pd_list, list) {
98                 if (entry->target_dev == devid ||
99                     entry->target_dev == alias) {
100                         ret = entry;
101                         break;
102                 }
103         }
104
105         spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
106
107         return ret;
108 }
109
110 /*
111  * This function checks if the driver got a valid device from the caller to
112  * avoid dereferencing invalid pointers.
113  */
114 static bool check_device(struct device *dev)
115 {
116         u16 devid;
117
118         if (!dev || !dev->dma_mask)
119                 return false;
120
121         /* No device or no PCI device */
122         if (dev->bus != &pci_bus_type)
123                 return false;
124
125         devid = get_device_id(dev);
126
127         /* Out of our scope? */
128         if (devid > amd_iommu_last_bdf)
129                 return false;
130
131         if (amd_iommu_rlookup_table[devid] == NULL)
132                 return false;
133
134         return true;
135 }
136
137 static int iommu_init_device(struct device *dev)
138 {
139         struct iommu_dev_data *dev_data;
140         struct pci_dev *pdev;
141         u16 devid, alias;
142
143         if (dev->archdata.iommu)
144                 return 0;
145
146         dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
147         if (!dev_data)
148                 return -ENOMEM;
149
150         dev_data->dev = dev;
151
152         devid = get_device_id(dev);
153         alias = amd_iommu_alias_table[devid];
154         pdev = pci_get_bus_and_slot(PCI_BUS(alias), alias & 0xff);
155         if (pdev)
156                 dev_data->alias = &pdev->dev;
157
158         atomic_set(&dev_data->bind, 0);
159
160         dev->archdata.iommu = dev_data;
161
162
163         return 0;
164 }
165
166 static void iommu_uninit_device(struct device *dev)
167 {
168         kfree(dev->archdata.iommu);
169 }
170
171 void __init amd_iommu_uninit_devices(void)
172 {
173         struct pci_dev *pdev = NULL;
174
175         for_each_pci_dev(pdev) {
176
177                 if (!check_device(&pdev->dev))
178                         continue;
179
180                 iommu_uninit_device(&pdev->dev);
181         }
182 }
183
184 int __init amd_iommu_init_devices(void)
185 {
186         struct pci_dev *pdev = NULL;
187         int ret = 0;
188
189         for_each_pci_dev(pdev) {
190
191                 if (!check_device(&pdev->dev))
192                         continue;
193
194                 ret = iommu_init_device(&pdev->dev);
195                 if (ret)
196                         goto out_free;
197         }
198
199         return 0;
200
201 out_free:
202
203         amd_iommu_uninit_devices();
204
205         return ret;
206 }
207 #ifdef CONFIG_AMD_IOMMU_STATS
208
209 /*
210  * Initialization code for statistics collection
211  */
212
213 DECLARE_STATS_COUNTER(compl_wait);
214 DECLARE_STATS_COUNTER(cnt_map_single);
215 DECLARE_STATS_COUNTER(cnt_unmap_single);
216 DECLARE_STATS_COUNTER(cnt_map_sg);
217 DECLARE_STATS_COUNTER(cnt_unmap_sg);
218 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
219 DECLARE_STATS_COUNTER(cnt_free_coherent);
220 DECLARE_STATS_COUNTER(cross_page);
221 DECLARE_STATS_COUNTER(domain_flush_single);
222 DECLARE_STATS_COUNTER(domain_flush_all);
223 DECLARE_STATS_COUNTER(alloced_io_mem);
224 DECLARE_STATS_COUNTER(total_map_requests);
225
226 static struct dentry *stats_dir;
227 static struct dentry *de_fflush;
228
229 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
230 {
231         if (stats_dir == NULL)
232                 return;
233
234         cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
235                                        &cnt->value);
236 }
237
238 static void amd_iommu_stats_init(void)
239 {
240         stats_dir = debugfs_create_dir("amd-iommu", NULL);
241         if (stats_dir == NULL)
242                 return;
243
244         de_fflush  = debugfs_create_bool("fullflush", 0444, stats_dir,
245                                          (u32 *)&amd_iommu_unmap_flush);
246
247         amd_iommu_stats_add(&compl_wait);
248         amd_iommu_stats_add(&cnt_map_single);
249         amd_iommu_stats_add(&cnt_unmap_single);
250         amd_iommu_stats_add(&cnt_map_sg);
251         amd_iommu_stats_add(&cnt_unmap_sg);
252         amd_iommu_stats_add(&cnt_alloc_coherent);
253         amd_iommu_stats_add(&cnt_free_coherent);
254         amd_iommu_stats_add(&cross_page);
255         amd_iommu_stats_add(&domain_flush_single);
256         amd_iommu_stats_add(&domain_flush_all);
257         amd_iommu_stats_add(&alloced_io_mem);
258         amd_iommu_stats_add(&total_map_requests);
259 }
260
261 #endif
262
263 /****************************************************************************
264  *
265  * Interrupt handling functions
266  *
267  ****************************************************************************/
268
269 static void dump_dte_entry(u16 devid)
270 {
271         int i;
272
273         for (i = 0; i < 8; ++i)
274                 pr_err("AMD-Vi: DTE[%d]: %08x\n", i,
275                         amd_iommu_dev_table[devid].data[i]);
276 }
277
278 static void dump_command(unsigned long phys_addr)
279 {
280         struct iommu_cmd *cmd = phys_to_virt(phys_addr);
281         int i;
282
283         for (i = 0; i < 4; ++i)
284                 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
285 }
286
287 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
288 {
289         u32 *event = __evt;
290         int type  = (event[1] >> EVENT_TYPE_SHIFT)  & EVENT_TYPE_MASK;
291         int devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
292         int domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
293         int flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
294         u64 address = (u64)(((u64)event[3]) << 32) | event[2];
295
296         printk(KERN_ERR "AMD-Vi: Event logged [");
297
298         switch (type) {
299         case EVENT_TYPE_ILL_DEV:
300                 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
301                        "address=0x%016llx flags=0x%04x]\n",
302                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
303                        address, flags);
304                 dump_dte_entry(devid);
305                 break;
306         case EVENT_TYPE_IO_FAULT:
307                 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
308                        "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
309                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
310                        domid, address, flags);
311                 break;
312         case EVENT_TYPE_DEV_TAB_ERR:
313                 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
314                        "address=0x%016llx flags=0x%04x]\n",
315                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
316                        address, flags);
317                 break;
318         case EVENT_TYPE_PAGE_TAB_ERR:
319                 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
320                        "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
321                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
322                        domid, address, flags);
323                 break;
324         case EVENT_TYPE_ILL_CMD:
325                 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
326                 iommu->reset_in_progress = true;
327                 reset_iommu_command_buffer(iommu);
328                 dump_command(address);
329                 break;
330         case EVENT_TYPE_CMD_HARD_ERR:
331                 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
332                        "flags=0x%04x]\n", address, flags);
333                 break;
334         case EVENT_TYPE_IOTLB_INV_TO:
335                 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
336                        "address=0x%016llx]\n",
337                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
338                        address);
339                 break;
340         case EVENT_TYPE_INV_DEV_REQ:
341                 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
342                        "address=0x%016llx flags=0x%04x]\n",
343                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
344                        address, flags);
345                 break;
346         default:
347                 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
348         }
349 }
350
351 static void iommu_poll_events(struct amd_iommu *iommu)
352 {
353         u32 head, tail;
354         unsigned long flags;
355
356         spin_lock_irqsave(&iommu->lock, flags);
357
358         head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
359         tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
360
361         while (head != tail) {
362                 iommu_print_event(iommu, iommu->evt_buf + head);
363                 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
364         }
365
366         writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
367
368         spin_unlock_irqrestore(&iommu->lock, flags);
369 }
370
371 irqreturn_t amd_iommu_int_handler(int irq, void *data)
372 {
373         struct amd_iommu *iommu;
374
375         for_each_iommu(iommu)
376                 iommu_poll_events(iommu);
377
378         return IRQ_HANDLED;
379 }
380
381 /****************************************************************************
382  *
383  * IOMMU command queuing functions
384  *
385  ****************************************************************************/
386
387 /*
388  * Writes the command to the IOMMUs command buffer and informs the
389  * hardware about the new command. Must be called with iommu->lock held.
390  */
391 static int __iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
392 {
393         u32 tail, head;
394         u8 *target;
395
396         WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
397         tail = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
398         target = iommu->cmd_buf + tail;
399         memcpy_toio(target, cmd, sizeof(*cmd));
400         tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
401         head = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
402         if (tail == head)
403                 return -ENOMEM;
404         writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
405
406         return 0;
407 }
408
409 /*
410  * General queuing function for commands. Takes iommu->lock and calls
411  * __iommu_queue_command().
412  */
413 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
414 {
415         unsigned long flags;
416         int ret;
417
418         spin_lock_irqsave(&iommu->lock, flags);
419         ret = __iommu_queue_command(iommu, cmd);
420         if (!ret)
421                 iommu->need_sync = true;
422         spin_unlock_irqrestore(&iommu->lock, flags);
423
424         return ret;
425 }
426
427 /*
428  * This function waits until an IOMMU has completed a completion
429  * wait command
430  */
431 static void __iommu_wait_for_completion(struct amd_iommu *iommu)
432 {
433         int ready = 0;
434         unsigned status = 0;
435         unsigned long i = 0;
436
437         INC_STATS_COUNTER(compl_wait);
438
439         while (!ready && (i < EXIT_LOOP_COUNT)) {
440                 ++i;
441                 /* wait for the bit to become one */
442                 status = readl(iommu->mmio_base + MMIO_STATUS_OFFSET);
443                 ready = status & MMIO_STATUS_COM_WAIT_INT_MASK;
444         }
445
446         /* set bit back to zero */
447         status &= ~MMIO_STATUS_COM_WAIT_INT_MASK;
448         writel(status, iommu->mmio_base + MMIO_STATUS_OFFSET);
449
450         if (unlikely(i == EXIT_LOOP_COUNT))
451                 iommu->reset_in_progress = true;
452 }
453
454 /*
455  * This function queues a completion wait command into the command
456  * buffer of an IOMMU
457  */
458 static int __iommu_completion_wait(struct amd_iommu *iommu)
459 {
460         struct iommu_cmd cmd;
461
462          memset(&cmd, 0, sizeof(cmd));
463          cmd.data[0] = CMD_COMPL_WAIT_INT_MASK;
464          CMD_SET_TYPE(&cmd, CMD_COMPL_WAIT);
465
466          return __iommu_queue_command(iommu, &cmd);
467 }
468
469 /*
470  * This function is called whenever we need to ensure that the IOMMU has
471  * completed execution of all commands we sent. It sends a
472  * COMPLETION_WAIT command and waits for it to finish. The IOMMU informs
473  * us about that by writing a value to a physical address we pass with
474  * the command.
475  */
476 static int iommu_completion_wait(struct amd_iommu *iommu)
477 {
478         int ret = 0;
479         unsigned long flags;
480
481         spin_lock_irqsave(&iommu->lock, flags);
482
483         if (!iommu->need_sync)
484                 goto out;
485
486         ret = __iommu_completion_wait(iommu);
487
488         iommu->need_sync = false;
489
490         if (ret)
491                 goto out;
492
493         __iommu_wait_for_completion(iommu);
494
495 out:
496         spin_unlock_irqrestore(&iommu->lock, flags);
497
498         if (iommu->reset_in_progress)
499                 reset_iommu_command_buffer(iommu);
500
501         return 0;
502 }
503
504 static void iommu_flush_complete(struct protection_domain *domain)
505 {
506         int i;
507
508         for (i = 0; i < amd_iommus_present; ++i) {
509                 if (!domain->dev_iommu[i])
510                         continue;
511
512                 /*
513                  * Devices of this domain are behind this IOMMU
514                  * We need to wait for completion of all commands.
515                  */
516                 iommu_completion_wait(amd_iommus[i]);
517         }
518 }
519
520 /*
521  * Command send function for invalidating a device table entry
522  */
523 static int iommu_flush_device(struct device *dev)
524 {
525         struct amd_iommu *iommu;
526         struct iommu_cmd cmd;
527         u16 devid;
528
529         devid = get_device_id(dev);
530         iommu = amd_iommu_rlookup_table[devid];
531
532         /* Build command */
533         memset(&cmd, 0, sizeof(cmd));
534         CMD_SET_TYPE(&cmd, CMD_INV_DEV_ENTRY);
535         cmd.data[0] = devid;
536
537         return iommu_queue_command(iommu, &cmd);
538 }
539
540 static void __iommu_build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
541                                           u16 domid, int pde, int s)
542 {
543         memset(cmd, 0, sizeof(*cmd));
544         address &= PAGE_MASK;
545         CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
546         cmd->data[1] |= domid;
547         cmd->data[2] = lower_32_bits(address);
548         cmd->data[3] = upper_32_bits(address);
549         if (s) /* size bit - we flush more than one 4kb page */
550                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
551         if (pde) /* PDE bit - we wan't flush everything not only the PTEs */
552                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
553 }
554
555 /*
556  * Generic command send function for invalidaing TLB entries
557  */
558 static int iommu_queue_inv_iommu_pages(struct amd_iommu *iommu,
559                 u64 address, u16 domid, int pde, int s)
560 {
561         struct iommu_cmd cmd;
562         int ret;
563
564         __iommu_build_inv_iommu_pages(&cmd, address, domid, pde, s);
565
566         ret = iommu_queue_command(iommu, &cmd);
567
568         return ret;
569 }
570
571 /*
572  * TLB invalidation function which is called from the mapping functions.
573  * It invalidates a single PTE if the range to flush is within a single
574  * page. Otherwise it flushes the whole TLB of the IOMMU.
575  */
576 static void __iommu_flush_pages(struct protection_domain *domain,
577                                 u64 address, size_t size, int pde)
578 {
579         int s = 0, i;
580         unsigned long pages = iommu_num_pages(address, size, PAGE_SIZE);
581
582         address &= PAGE_MASK;
583
584         if (pages > 1) {
585                 /*
586                  * If we have to flush more than one page, flush all
587                  * TLB entries for this domain
588                  */
589                 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
590                 s = 1;
591         }
592
593
594         for (i = 0; i < amd_iommus_present; ++i) {
595                 if (!domain->dev_iommu[i])
596                         continue;
597
598                 /*
599                  * Devices of this domain are behind this IOMMU
600                  * We need a TLB flush
601                  */
602                 iommu_queue_inv_iommu_pages(amd_iommus[i], address,
603                                             domain->id, pde, s);
604         }
605
606         return;
607 }
608
609 static void iommu_flush_pages(struct protection_domain *domain,
610                              u64 address, size_t size)
611 {
612         __iommu_flush_pages(domain, address, size, 0);
613 }
614
615 /* Flush the whole IO/TLB for a given protection domain */
616 static void iommu_flush_tlb(struct protection_domain *domain)
617 {
618         __iommu_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
619 }
620
621 /* Flush the whole IO/TLB for a given protection domain - including PDE */
622 static void iommu_flush_tlb_pde(struct protection_domain *domain)
623 {
624         __iommu_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
625 }
626
627
628 /*
629  * This function flushes the DTEs for all devices in domain
630  */
631 static void iommu_flush_domain_devices(struct protection_domain *domain)
632 {
633         struct iommu_dev_data *dev_data;
634         unsigned long flags;
635
636         spin_lock_irqsave(&domain->lock, flags);
637
638         list_for_each_entry(dev_data, &domain->dev_list, list)
639                 iommu_flush_device(dev_data->dev);
640
641         spin_unlock_irqrestore(&domain->lock, flags);
642 }
643
644 static void iommu_flush_all_domain_devices(void)
645 {
646         struct protection_domain *domain;
647         unsigned long flags;
648
649         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
650
651         list_for_each_entry(domain, &amd_iommu_pd_list, list) {
652                 iommu_flush_domain_devices(domain);
653                 iommu_flush_complete(domain);
654         }
655
656         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
657 }
658
659 void amd_iommu_flush_all_devices(void)
660 {
661         iommu_flush_all_domain_devices();
662 }
663
664 /*
665  * This function uses heavy locking and may disable irqs for some time. But
666  * this is no issue because it is only called during resume.
667  */
668 void amd_iommu_flush_all_domains(void)
669 {
670         struct protection_domain *domain;
671         unsigned long flags;
672
673         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
674
675         list_for_each_entry(domain, &amd_iommu_pd_list, list) {
676                 spin_lock(&domain->lock);
677                 iommu_flush_tlb_pde(domain);
678                 iommu_flush_complete(domain);
679                 spin_unlock(&domain->lock);
680         }
681
682         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
683 }
684
685 static void reset_iommu_command_buffer(struct amd_iommu *iommu)
686 {
687         pr_err("AMD-Vi: Resetting IOMMU command buffer\n");
688
689         if (iommu->reset_in_progress)
690                 panic("AMD-Vi: ILLEGAL_COMMAND_ERROR while resetting command buffer\n");
691
692         amd_iommu_reset_cmd_buffer(iommu);
693         amd_iommu_flush_all_devices();
694         amd_iommu_flush_all_domains();
695
696         iommu->reset_in_progress = false;
697 }
698
699 /****************************************************************************
700  *
701  * The functions below are used the create the page table mappings for
702  * unity mapped regions.
703  *
704  ****************************************************************************/
705
706 /*
707  * This function is used to add another level to an IO page table. Adding
708  * another level increases the size of the address space by 9 bits to a size up
709  * to 64 bits.
710  */
711 static bool increase_address_space(struct protection_domain *domain,
712                                    gfp_t gfp)
713 {
714         u64 *pte;
715
716         if (domain->mode == PAGE_MODE_6_LEVEL)
717                 /* address space already 64 bit large */
718                 return false;
719
720         pte = (void *)get_zeroed_page(gfp);
721         if (!pte)
722                 return false;
723
724         *pte             = PM_LEVEL_PDE(domain->mode,
725                                         virt_to_phys(domain->pt_root));
726         domain->pt_root  = pte;
727         domain->mode    += 1;
728         domain->updated  = true;
729
730         return true;
731 }
732
733 static u64 *alloc_pte(struct protection_domain *domain,
734                       unsigned long address,
735                       unsigned long page_size,
736                       u64 **pte_page,
737                       gfp_t gfp)
738 {
739         int level, end_lvl;
740         u64 *pte, *page;
741
742         BUG_ON(!is_power_of_2(page_size));
743
744         while (address > PM_LEVEL_SIZE(domain->mode))
745                 increase_address_space(domain, gfp);
746
747         level   = domain->mode - 1;
748         pte     = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
749         address = PAGE_SIZE_ALIGN(address, page_size);
750         end_lvl = PAGE_SIZE_LEVEL(page_size);
751
752         while (level > end_lvl) {
753                 if (!IOMMU_PTE_PRESENT(*pte)) {
754                         page = (u64 *)get_zeroed_page(gfp);
755                         if (!page)
756                                 return NULL;
757                         *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
758                 }
759
760                 /* No level skipping support yet */
761                 if (PM_PTE_LEVEL(*pte) != level)
762                         return NULL;
763
764                 level -= 1;
765
766                 pte = IOMMU_PTE_PAGE(*pte);
767
768                 if (pte_page && level == end_lvl)
769                         *pte_page = pte;
770
771                 pte = &pte[PM_LEVEL_INDEX(level, address)];
772         }
773
774         return pte;
775 }
776
777 /*
778  * This function checks if there is a PTE for a given dma address. If
779  * there is one, it returns the pointer to it.
780  */
781 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
782 {
783         int level;
784         u64 *pte;
785
786         if (address > PM_LEVEL_SIZE(domain->mode))
787                 return NULL;
788
789         level   =  domain->mode - 1;
790         pte     = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
791
792         while (level > 0) {
793
794                 /* Not Present */
795                 if (!IOMMU_PTE_PRESENT(*pte))
796                         return NULL;
797
798                 /* Large PTE */
799                 if (PM_PTE_LEVEL(*pte) == 0x07) {
800                         unsigned long pte_mask, __pte;
801
802                         /*
803                          * If we have a series of large PTEs, make
804                          * sure to return a pointer to the first one.
805                          */
806                         pte_mask = PTE_PAGE_SIZE(*pte);
807                         pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
808                         __pte    = ((unsigned long)pte) & pte_mask;
809
810                         return (u64 *)__pte;
811                 }
812
813                 /* No level skipping support yet */
814                 if (PM_PTE_LEVEL(*pte) != level)
815                         return NULL;
816
817                 level -= 1;
818
819                 /* Walk to the next level */
820                 pte = IOMMU_PTE_PAGE(*pte);
821                 pte = &pte[PM_LEVEL_INDEX(level, address)];
822         }
823
824         return pte;
825 }
826
827 /*
828  * Generic mapping functions. It maps a physical address into a DMA
829  * address space. It allocates the page table pages if necessary.
830  * In the future it can be extended to a generic mapping function
831  * supporting all features of AMD IOMMU page tables like level skipping
832  * and full 64 bit address spaces.
833  */
834 static int iommu_map_page(struct protection_domain *dom,
835                           unsigned long bus_addr,
836                           unsigned long phys_addr,
837                           int prot,
838                           unsigned long page_size)
839 {
840         u64 __pte, *pte;
841         int i, count;
842
843         if (!(prot & IOMMU_PROT_MASK))
844                 return -EINVAL;
845
846         bus_addr  = PAGE_ALIGN(bus_addr);
847         phys_addr = PAGE_ALIGN(phys_addr);
848         count     = PAGE_SIZE_PTE_COUNT(page_size);
849         pte       = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
850
851         for (i = 0; i < count; ++i)
852                 if (IOMMU_PTE_PRESENT(pte[i]))
853                         return -EBUSY;
854
855         if (page_size > PAGE_SIZE) {
856                 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
857                 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
858         } else
859                 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
860
861         if (prot & IOMMU_PROT_IR)
862                 __pte |= IOMMU_PTE_IR;
863         if (prot & IOMMU_PROT_IW)
864                 __pte |= IOMMU_PTE_IW;
865
866         for (i = 0; i < count; ++i)
867                 pte[i] = __pte;
868
869         update_domain(dom);
870
871         return 0;
872 }
873
874 static unsigned long iommu_unmap_page(struct protection_domain *dom,
875                                       unsigned long bus_addr,
876                                       unsigned long page_size)
877 {
878         unsigned long long unmap_size, unmapped;
879         u64 *pte;
880
881         BUG_ON(!is_power_of_2(page_size));
882
883         unmapped = 0;
884
885         while (unmapped < page_size) {
886
887                 pte = fetch_pte(dom, bus_addr);
888
889                 if (!pte) {
890                         /*
891                          * No PTE for this address
892                          * move forward in 4kb steps
893                          */
894                         unmap_size = PAGE_SIZE;
895                 } else if (PM_PTE_LEVEL(*pte) == 0) {
896                         /* 4kb PTE found for this address */
897                         unmap_size = PAGE_SIZE;
898                         *pte       = 0ULL;
899                 } else {
900                         int count, i;
901
902                         /* Large PTE found which maps this address */
903                         unmap_size = PTE_PAGE_SIZE(*pte);
904                         count      = PAGE_SIZE_PTE_COUNT(unmap_size);
905                         for (i = 0; i < count; i++)
906                                 pte[i] = 0ULL;
907                 }
908
909                 bus_addr  = (bus_addr & ~(unmap_size - 1)) + unmap_size;
910                 unmapped += unmap_size;
911         }
912
913         BUG_ON(!is_power_of_2(unmapped));
914
915         return unmapped;
916 }
917
918 /*
919  * This function checks if a specific unity mapping entry is needed for
920  * this specific IOMMU.
921  */
922 static int iommu_for_unity_map(struct amd_iommu *iommu,
923                                struct unity_map_entry *entry)
924 {
925         u16 bdf, i;
926
927         for (i = entry->devid_start; i <= entry->devid_end; ++i) {
928                 bdf = amd_iommu_alias_table[i];
929                 if (amd_iommu_rlookup_table[bdf] == iommu)
930                         return 1;
931         }
932
933         return 0;
934 }
935
936 /*
937  * This function actually applies the mapping to the page table of the
938  * dma_ops domain.
939  */
940 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
941                              struct unity_map_entry *e)
942 {
943         u64 addr;
944         int ret;
945
946         for (addr = e->address_start; addr < e->address_end;
947              addr += PAGE_SIZE) {
948                 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
949                                      PAGE_SIZE);
950                 if (ret)
951                         return ret;
952                 /*
953                  * if unity mapping is in aperture range mark the page
954                  * as allocated in the aperture
955                  */
956                 if (addr < dma_dom->aperture_size)
957                         __set_bit(addr >> PAGE_SHIFT,
958                                   dma_dom->aperture[0]->bitmap);
959         }
960
961         return 0;
962 }
963
964 /*
965  * Init the unity mappings for a specific IOMMU in the system
966  *
967  * Basically iterates over all unity mapping entries and applies them to
968  * the default domain DMA of that IOMMU if necessary.
969  */
970 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
971 {
972         struct unity_map_entry *entry;
973         int ret;
974
975         list_for_each_entry(entry, &amd_iommu_unity_map, list) {
976                 if (!iommu_for_unity_map(iommu, entry))
977                         continue;
978                 ret = dma_ops_unity_map(iommu->default_dom, entry);
979                 if (ret)
980                         return ret;
981         }
982
983         return 0;
984 }
985
986 /*
987  * Inits the unity mappings required for a specific device
988  */
989 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
990                                           u16 devid)
991 {
992         struct unity_map_entry *e;
993         int ret;
994
995         list_for_each_entry(e, &amd_iommu_unity_map, list) {
996                 if (!(devid >= e->devid_start && devid <= e->devid_end))
997                         continue;
998                 ret = dma_ops_unity_map(dma_dom, e);
999                 if (ret)
1000                         return ret;
1001         }
1002
1003         return 0;
1004 }
1005
1006 /****************************************************************************
1007  *
1008  * The next functions belong to the address allocator for the dma_ops
1009  * interface functions. They work like the allocators in the other IOMMU
1010  * drivers. Its basically a bitmap which marks the allocated pages in
1011  * the aperture. Maybe it could be enhanced in the future to a more
1012  * efficient allocator.
1013  *
1014  ****************************************************************************/
1015
1016 /*
1017  * The address allocator core functions.
1018  *
1019  * called with domain->lock held
1020  */
1021
1022 /*
1023  * Used to reserve address ranges in the aperture (e.g. for exclusion
1024  * ranges.
1025  */
1026 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1027                                       unsigned long start_page,
1028                                       unsigned int pages)
1029 {
1030         unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1031
1032         if (start_page + pages > last_page)
1033                 pages = last_page - start_page;
1034
1035         for (i = start_page; i < start_page + pages; ++i) {
1036                 int index = i / APERTURE_RANGE_PAGES;
1037                 int page  = i % APERTURE_RANGE_PAGES;
1038                 __set_bit(page, dom->aperture[index]->bitmap);
1039         }
1040 }
1041
1042 /*
1043  * This function is used to add a new aperture range to an existing
1044  * aperture in case of dma_ops domain allocation or address allocation
1045  * failure.
1046  */
1047 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1048                            bool populate, gfp_t gfp)
1049 {
1050         int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1051         struct amd_iommu *iommu;
1052         unsigned long i, old_size;
1053
1054 #ifdef CONFIG_IOMMU_STRESS
1055         populate = false;
1056 #endif
1057
1058         if (index >= APERTURE_MAX_RANGES)
1059                 return -ENOMEM;
1060
1061         dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1062         if (!dma_dom->aperture[index])
1063                 return -ENOMEM;
1064
1065         dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1066         if (!dma_dom->aperture[index]->bitmap)
1067                 goto out_free;
1068
1069         dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1070
1071         if (populate) {
1072                 unsigned long address = dma_dom->aperture_size;
1073                 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1074                 u64 *pte, *pte_page;
1075
1076                 for (i = 0; i < num_ptes; ++i) {
1077                         pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1078                                         &pte_page, gfp);
1079                         if (!pte)
1080                                 goto out_free;
1081
1082                         dma_dom->aperture[index]->pte_pages[i] = pte_page;
1083
1084                         address += APERTURE_RANGE_SIZE / 64;
1085                 }
1086         }
1087
1088         old_size                = dma_dom->aperture_size;
1089         dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1090
1091         /* Reserve address range used for MSI messages */
1092         if (old_size < MSI_ADDR_BASE_LO &&
1093             dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1094                 unsigned long spage;
1095                 int pages;
1096
1097                 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1098                 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1099
1100                 dma_ops_reserve_addresses(dma_dom, spage, pages);
1101         }
1102
1103         /* Intialize the exclusion range if necessary */
1104         for_each_iommu(iommu) {
1105                 if (iommu->exclusion_start &&
1106                     iommu->exclusion_start >= dma_dom->aperture[index]->offset
1107                     && iommu->exclusion_start < dma_dom->aperture_size) {
1108                         unsigned long startpage;
1109                         int pages = iommu_num_pages(iommu->exclusion_start,
1110                                                     iommu->exclusion_length,
1111                                                     PAGE_SIZE);
1112                         startpage = iommu->exclusion_start >> PAGE_SHIFT;
1113                         dma_ops_reserve_addresses(dma_dom, startpage, pages);
1114                 }
1115         }
1116
1117         /*
1118          * Check for areas already mapped as present in the new aperture
1119          * range and mark those pages as reserved in the allocator. Such
1120          * mappings may already exist as a result of requested unity
1121          * mappings for devices.
1122          */
1123         for (i = dma_dom->aperture[index]->offset;
1124              i < dma_dom->aperture_size;
1125              i += PAGE_SIZE) {
1126                 u64 *pte = fetch_pte(&dma_dom->domain, i);
1127                 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1128                         continue;
1129
1130                 dma_ops_reserve_addresses(dma_dom, i << PAGE_SHIFT, 1);
1131         }
1132
1133         update_domain(&dma_dom->domain);
1134
1135         return 0;
1136
1137 out_free:
1138         update_domain(&dma_dom->domain);
1139
1140         free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1141
1142         kfree(dma_dom->aperture[index]);
1143         dma_dom->aperture[index] = NULL;
1144
1145         return -ENOMEM;
1146 }
1147
1148 static unsigned long dma_ops_area_alloc(struct device *dev,
1149                                         struct dma_ops_domain *dom,
1150                                         unsigned int pages,
1151                                         unsigned long align_mask,
1152                                         u64 dma_mask,
1153                                         unsigned long start)
1154 {
1155         unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1156         int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1157         int i = start >> APERTURE_RANGE_SHIFT;
1158         unsigned long boundary_size;
1159         unsigned long address = -1;
1160         unsigned long limit;
1161
1162         next_bit >>= PAGE_SHIFT;
1163
1164         boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1165                         PAGE_SIZE) >> PAGE_SHIFT;
1166
1167         for (;i < max_index; ++i) {
1168                 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1169
1170                 if (dom->aperture[i]->offset >= dma_mask)
1171                         break;
1172
1173                 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1174                                                dma_mask >> PAGE_SHIFT);
1175
1176                 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1177                                            limit, next_bit, pages, 0,
1178                                             boundary_size, align_mask);
1179                 if (address != -1) {
1180                         address = dom->aperture[i]->offset +
1181                                   (address << PAGE_SHIFT);
1182                         dom->next_address = address + (pages << PAGE_SHIFT);
1183                         break;
1184                 }
1185
1186                 next_bit = 0;
1187         }
1188
1189         return address;
1190 }
1191
1192 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1193                                              struct dma_ops_domain *dom,
1194                                              unsigned int pages,
1195                                              unsigned long align_mask,
1196                                              u64 dma_mask)
1197 {
1198         unsigned long address;
1199
1200 #ifdef CONFIG_IOMMU_STRESS
1201         dom->next_address = 0;
1202         dom->need_flush = true;
1203 #endif
1204
1205         address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1206                                      dma_mask, dom->next_address);
1207
1208         if (address == -1) {
1209                 dom->next_address = 0;
1210                 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1211                                              dma_mask, 0);
1212                 dom->need_flush = true;
1213         }
1214
1215         if (unlikely(address == -1))
1216                 address = DMA_ERROR_CODE;
1217
1218         WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1219
1220         return address;
1221 }
1222
1223 /*
1224  * The address free function.
1225  *
1226  * called with domain->lock held
1227  */
1228 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1229                                    unsigned long address,
1230                                    unsigned int pages)
1231 {
1232         unsigned i = address >> APERTURE_RANGE_SHIFT;
1233         struct aperture_range *range = dom->aperture[i];
1234
1235         BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1236
1237 #ifdef CONFIG_IOMMU_STRESS
1238         if (i < 4)
1239                 return;
1240 #endif
1241
1242         if (address >= dom->next_address)
1243                 dom->need_flush = true;
1244
1245         address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1246
1247         bitmap_clear(range->bitmap, address, pages);
1248
1249 }
1250
1251 /****************************************************************************
1252  *
1253  * The next functions belong to the domain allocation. A domain is
1254  * allocated for every IOMMU as the default domain. If device isolation
1255  * is enabled, every device get its own domain. The most important thing
1256  * about domains is the page table mapping the DMA address space they
1257  * contain.
1258  *
1259  ****************************************************************************/
1260
1261 /*
1262  * This function adds a protection domain to the global protection domain list
1263  */
1264 static void add_domain_to_list(struct protection_domain *domain)
1265 {
1266         unsigned long flags;
1267
1268         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1269         list_add(&domain->list, &amd_iommu_pd_list);
1270         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1271 }
1272
1273 /*
1274  * This function removes a protection domain to the global
1275  * protection domain list
1276  */
1277 static void del_domain_from_list(struct protection_domain *domain)
1278 {
1279         unsigned long flags;
1280
1281         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1282         list_del(&domain->list);
1283         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1284 }
1285
1286 static u16 domain_id_alloc(void)
1287 {
1288         unsigned long flags;
1289         int id;
1290
1291         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1292         id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1293         BUG_ON(id == 0);
1294         if (id > 0 && id < MAX_DOMAIN_ID)
1295                 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1296         else
1297                 id = 0;
1298         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1299
1300         return id;
1301 }
1302
1303 static void domain_id_free(int id)
1304 {
1305         unsigned long flags;
1306
1307         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1308         if (id > 0 && id < MAX_DOMAIN_ID)
1309                 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1310         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1311 }
1312
1313 static void free_pagetable(struct protection_domain *domain)
1314 {
1315         int i, j;
1316         u64 *p1, *p2, *p3;
1317
1318         p1 = domain->pt_root;
1319
1320         if (!p1)
1321                 return;
1322
1323         for (i = 0; i < 512; ++i) {
1324                 if (!IOMMU_PTE_PRESENT(p1[i]))
1325                         continue;
1326
1327                 p2 = IOMMU_PTE_PAGE(p1[i]);
1328                 for (j = 0; j < 512; ++j) {
1329                         if (!IOMMU_PTE_PRESENT(p2[j]))
1330                                 continue;
1331                         p3 = IOMMU_PTE_PAGE(p2[j]);
1332                         free_page((unsigned long)p3);
1333                 }
1334
1335                 free_page((unsigned long)p2);
1336         }
1337
1338         free_page((unsigned long)p1);
1339
1340         domain->pt_root = NULL;
1341 }
1342
1343 /*
1344  * Free a domain, only used if something went wrong in the
1345  * allocation path and we need to free an already allocated page table
1346  */
1347 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1348 {
1349         int i;
1350
1351         if (!dom)
1352                 return;
1353
1354         del_domain_from_list(&dom->domain);
1355
1356         free_pagetable(&dom->domain);
1357
1358         for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1359                 if (!dom->aperture[i])
1360                         continue;
1361                 free_page((unsigned long)dom->aperture[i]->bitmap);
1362                 kfree(dom->aperture[i]);
1363         }
1364
1365         kfree(dom);
1366 }
1367
1368 /*
1369  * Allocates a new protection domain usable for the dma_ops functions.
1370  * It also intializes the page table and the address allocator data
1371  * structures required for the dma_ops interface
1372  */
1373 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1374 {
1375         struct dma_ops_domain *dma_dom;
1376
1377         dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1378         if (!dma_dom)
1379                 return NULL;
1380
1381         spin_lock_init(&dma_dom->domain.lock);
1382
1383         dma_dom->domain.id = domain_id_alloc();
1384         if (dma_dom->domain.id == 0)
1385                 goto free_dma_dom;
1386         INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1387         dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1388         dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1389         dma_dom->domain.flags = PD_DMA_OPS_MASK;
1390         dma_dom->domain.priv = dma_dom;
1391         if (!dma_dom->domain.pt_root)
1392                 goto free_dma_dom;
1393
1394         dma_dom->need_flush = false;
1395         dma_dom->target_dev = 0xffff;
1396
1397         add_domain_to_list(&dma_dom->domain);
1398
1399         if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1400                 goto free_dma_dom;
1401
1402         /*
1403          * mark the first page as allocated so we never return 0 as
1404          * a valid dma-address. So we can use 0 as error value
1405          */
1406         dma_dom->aperture[0]->bitmap[0] = 1;
1407         dma_dom->next_address = 0;
1408
1409
1410         return dma_dom;
1411
1412 free_dma_dom:
1413         dma_ops_domain_free(dma_dom);
1414
1415         return NULL;
1416 }
1417
1418 /*
1419  * little helper function to check whether a given protection domain is a
1420  * dma_ops domain
1421  */
1422 static bool dma_ops_domain(struct protection_domain *domain)
1423 {
1424         return domain->flags & PD_DMA_OPS_MASK;
1425 }
1426
1427 static void set_dte_entry(u16 devid, struct protection_domain *domain)
1428 {
1429         u64 pte_root = virt_to_phys(domain->pt_root);
1430
1431         pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1432                     << DEV_ENTRY_MODE_SHIFT;
1433         pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1434
1435         amd_iommu_dev_table[devid].data[2] = domain->id;
1436         amd_iommu_dev_table[devid].data[1] = upper_32_bits(pte_root);
1437         amd_iommu_dev_table[devid].data[0] = lower_32_bits(pte_root);
1438 }
1439
1440 static void clear_dte_entry(u16 devid)
1441 {
1442         /* remove entry from the device table seen by the hardware */
1443         amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1444         amd_iommu_dev_table[devid].data[1] = 0;
1445         amd_iommu_dev_table[devid].data[2] = 0;
1446
1447         amd_iommu_apply_erratum_63(devid);
1448 }
1449
1450 static void do_attach(struct device *dev, struct protection_domain *domain)
1451 {
1452         struct iommu_dev_data *dev_data;
1453         struct amd_iommu *iommu;
1454         u16 devid;
1455
1456         devid    = get_device_id(dev);
1457         iommu    = amd_iommu_rlookup_table[devid];
1458         dev_data = get_dev_data(dev);
1459
1460         /* Update data structures */
1461         dev_data->domain = domain;
1462         list_add(&dev_data->list, &domain->dev_list);
1463         set_dte_entry(devid, domain);
1464
1465         /* Do reference counting */
1466         domain->dev_iommu[iommu->index] += 1;
1467         domain->dev_cnt                 += 1;
1468
1469         /* Flush the DTE entry */
1470         iommu_flush_device(dev);
1471 }
1472
1473 static void do_detach(struct device *dev)
1474 {
1475         struct iommu_dev_data *dev_data;
1476         struct amd_iommu *iommu;
1477         u16 devid;
1478
1479         devid    = get_device_id(dev);
1480         iommu    = amd_iommu_rlookup_table[devid];
1481         dev_data = get_dev_data(dev);
1482
1483         /* decrease reference counters */
1484         dev_data->domain->dev_iommu[iommu->index] -= 1;
1485         dev_data->domain->dev_cnt                 -= 1;
1486
1487         /* Update data structures */
1488         dev_data->domain = NULL;
1489         list_del(&dev_data->list);
1490         clear_dte_entry(devid);
1491
1492         /* Flush the DTE entry */
1493         iommu_flush_device(dev);
1494 }
1495
1496 /*
1497  * If a device is not yet associated with a domain, this function does
1498  * assigns it visible for the hardware
1499  */
1500 static int __attach_device(struct device *dev,
1501                            struct protection_domain *domain)
1502 {
1503         struct iommu_dev_data *dev_data, *alias_data;
1504         int ret;
1505
1506         dev_data   = get_dev_data(dev);
1507         alias_data = get_dev_data(dev_data->alias);
1508
1509         if (!alias_data)
1510                 return -EINVAL;
1511
1512         /* lock domain */
1513         spin_lock(&domain->lock);
1514
1515         /* Some sanity checks */
1516         ret = -EBUSY;
1517         if (alias_data->domain != NULL &&
1518             alias_data->domain != domain)
1519                 goto out_unlock;
1520
1521         if (dev_data->domain != NULL &&
1522             dev_data->domain != domain)
1523                 goto out_unlock;
1524
1525         /* Do real assignment */
1526         if (dev_data->alias != dev) {
1527                 alias_data = get_dev_data(dev_data->alias);
1528                 if (alias_data->domain == NULL)
1529                         do_attach(dev_data->alias, domain);
1530
1531                 atomic_inc(&alias_data->bind);
1532         }
1533
1534         if (dev_data->domain == NULL)
1535                 do_attach(dev, domain);
1536
1537         atomic_inc(&dev_data->bind);
1538
1539         ret = 0;
1540
1541 out_unlock:
1542
1543         /* ready */
1544         spin_unlock(&domain->lock);
1545
1546         return ret;
1547 }
1548
1549 /*
1550  * If a device is not yet associated with a domain, this function does
1551  * assigns it visible for the hardware
1552  */
1553 static int attach_device(struct device *dev,
1554                          struct protection_domain *domain)
1555 {
1556         unsigned long flags;
1557         int ret;
1558
1559         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1560         ret = __attach_device(dev, domain);
1561         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1562
1563         /*
1564          * We might boot into a crash-kernel here. The crashed kernel
1565          * left the caches in the IOMMU dirty. So we have to flush
1566          * here to evict all dirty stuff.
1567          */
1568         iommu_flush_tlb_pde(domain);
1569
1570         return ret;
1571 }
1572
1573 /*
1574  * Removes a device from a protection domain (unlocked)
1575  */
1576 static void __detach_device(struct device *dev)
1577 {
1578         struct iommu_dev_data *dev_data = get_dev_data(dev);
1579         struct iommu_dev_data *alias_data;
1580         struct protection_domain *domain;
1581         unsigned long flags;
1582
1583         BUG_ON(!dev_data->domain);
1584
1585         domain = dev_data->domain;
1586
1587         spin_lock_irqsave(&domain->lock, flags);
1588
1589         if (dev_data->alias != dev) {
1590                 alias_data = get_dev_data(dev_data->alias);
1591                 if (atomic_dec_and_test(&alias_data->bind))
1592                         do_detach(dev_data->alias);
1593         }
1594
1595         if (atomic_dec_and_test(&dev_data->bind))
1596                 do_detach(dev);
1597
1598         spin_unlock_irqrestore(&domain->lock, flags);
1599
1600         /*
1601          * If we run in passthrough mode the device must be assigned to the
1602          * passthrough domain if it is detached from any other domain.
1603          * Make sure we can deassign from the pt_domain itself.
1604          */
1605         if (iommu_pass_through &&
1606             (dev_data->domain == NULL && domain != pt_domain))
1607                 __attach_device(dev, pt_domain);
1608 }
1609
1610 /*
1611  * Removes a device from a protection domain (with devtable_lock held)
1612  */
1613 static void detach_device(struct device *dev)
1614 {
1615         unsigned long flags;
1616
1617         /* lock device table */
1618         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1619         __detach_device(dev);
1620         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1621 }
1622
1623 /*
1624  * Find out the protection domain structure for a given PCI device. This
1625  * will give us the pointer to the page table root for example.
1626  */
1627 static struct protection_domain *domain_for_device(struct device *dev)
1628 {
1629         struct protection_domain *dom;
1630         struct iommu_dev_data *dev_data, *alias_data;
1631         unsigned long flags;
1632         u16 devid, alias;
1633
1634         devid      = get_device_id(dev);
1635         alias      = amd_iommu_alias_table[devid];
1636         dev_data   = get_dev_data(dev);
1637         alias_data = get_dev_data(dev_data->alias);
1638         if (!alias_data)
1639                 return NULL;
1640
1641         read_lock_irqsave(&amd_iommu_devtable_lock, flags);
1642         dom = dev_data->domain;
1643         if (dom == NULL &&
1644             alias_data->domain != NULL) {
1645                 __attach_device(dev, alias_data->domain);
1646                 dom = alias_data->domain;
1647         }
1648
1649         read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1650
1651         return dom;
1652 }
1653
1654 static int device_change_notifier(struct notifier_block *nb,
1655                                   unsigned long action, void *data)
1656 {
1657         struct device *dev = data;
1658         u16 devid;
1659         struct protection_domain *domain;
1660         struct dma_ops_domain *dma_domain;
1661         struct amd_iommu *iommu;
1662         unsigned long flags;
1663
1664         if (!check_device(dev))
1665                 return 0;
1666
1667         devid  = get_device_id(dev);
1668         iommu  = amd_iommu_rlookup_table[devid];
1669
1670         switch (action) {
1671         case BUS_NOTIFY_UNBOUND_DRIVER:
1672
1673                 domain = domain_for_device(dev);
1674
1675                 if (!domain)
1676                         goto out;
1677                 if (iommu_pass_through)
1678                         break;
1679                 detach_device(dev);
1680                 break;
1681         case BUS_NOTIFY_ADD_DEVICE:
1682
1683                 iommu_init_device(dev);
1684
1685                 domain = domain_for_device(dev);
1686
1687                 /* allocate a protection domain if a device is added */
1688                 dma_domain = find_protection_domain(devid);
1689                 if (dma_domain)
1690                         goto out;
1691                 dma_domain = dma_ops_domain_alloc();
1692                 if (!dma_domain)
1693                         goto out;
1694                 dma_domain->target_dev = devid;
1695
1696                 spin_lock_irqsave(&iommu_pd_list_lock, flags);
1697                 list_add_tail(&dma_domain->list, &iommu_pd_list);
1698                 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
1699
1700                 break;
1701         case BUS_NOTIFY_DEL_DEVICE:
1702
1703                 iommu_uninit_device(dev);
1704
1705         default:
1706                 goto out;
1707         }
1708
1709         iommu_flush_device(dev);
1710         iommu_completion_wait(iommu);
1711
1712 out:
1713         return 0;
1714 }
1715
1716 static struct notifier_block device_nb = {
1717         .notifier_call = device_change_notifier,
1718 };
1719
1720 void amd_iommu_init_notifier(void)
1721 {
1722         bus_register_notifier(&pci_bus_type, &device_nb);
1723 }
1724
1725 /*****************************************************************************
1726  *
1727  * The next functions belong to the dma_ops mapping/unmapping code.
1728  *
1729  *****************************************************************************/
1730
1731 /*
1732  * In the dma_ops path we only have the struct device. This function
1733  * finds the corresponding IOMMU, the protection domain and the
1734  * requestor id for a given device.
1735  * If the device is not yet associated with a domain this is also done
1736  * in this function.
1737  */
1738 static struct protection_domain *get_domain(struct device *dev)
1739 {
1740         struct protection_domain *domain;
1741         struct dma_ops_domain *dma_dom;
1742         u16 devid = get_device_id(dev);
1743
1744         if (!check_device(dev))
1745                 return ERR_PTR(-EINVAL);
1746
1747         domain = domain_for_device(dev);
1748         if (domain != NULL && !dma_ops_domain(domain))
1749                 return ERR_PTR(-EBUSY);
1750
1751         if (domain != NULL)
1752                 return domain;
1753
1754         /* Device not bount yet - bind it */
1755         dma_dom = find_protection_domain(devid);
1756         if (!dma_dom)
1757                 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
1758         attach_device(dev, &dma_dom->domain);
1759         DUMP_printk("Using protection domain %d for device %s\n",
1760                     dma_dom->domain.id, dev_name(dev));
1761
1762         return &dma_dom->domain;
1763 }
1764
1765 static void update_device_table(struct protection_domain *domain)
1766 {
1767         struct iommu_dev_data *dev_data;
1768
1769         list_for_each_entry(dev_data, &domain->dev_list, list) {
1770                 u16 devid = get_device_id(dev_data->dev);
1771                 set_dte_entry(devid, domain);
1772         }
1773 }
1774
1775 static void update_domain(struct protection_domain *domain)
1776 {
1777         if (!domain->updated)
1778                 return;
1779
1780         update_device_table(domain);
1781         iommu_flush_domain_devices(domain);
1782         iommu_flush_tlb_pde(domain);
1783
1784         domain->updated = false;
1785 }
1786
1787 /*
1788  * This function fetches the PTE for a given address in the aperture
1789  */
1790 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
1791                             unsigned long address)
1792 {
1793         struct aperture_range *aperture;
1794         u64 *pte, *pte_page;
1795
1796         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
1797         if (!aperture)
1798                 return NULL;
1799
1800         pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
1801         if (!pte) {
1802                 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
1803                                 GFP_ATOMIC);
1804                 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
1805         } else
1806                 pte += PM_LEVEL_INDEX(0, address);
1807
1808         update_domain(&dom->domain);
1809
1810         return pte;
1811 }
1812
1813 /*
1814  * This is the generic map function. It maps one 4kb page at paddr to
1815  * the given address in the DMA address space for the domain.
1816  */
1817 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
1818                                      unsigned long address,
1819                                      phys_addr_t paddr,
1820                                      int direction)
1821 {
1822         u64 *pte, __pte;
1823
1824         WARN_ON(address > dom->aperture_size);
1825
1826         paddr &= PAGE_MASK;
1827
1828         pte  = dma_ops_get_pte(dom, address);
1829         if (!pte)
1830                 return DMA_ERROR_CODE;
1831
1832         __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
1833
1834         if (direction == DMA_TO_DEVICE)
1835                 __pte |= IOMMU_PTE_IR;
1836         else if (direction == DMA_FROM_DEVICE)
1837                 __pte |= IOMMU_PTE_IW;
1838         else if (direction == DMA_BIDIRECTIONAL)
1839                 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
1840
1841         WARN_ON(*pte);
1842
1843         *pte = __pte;
1844
1845         return (dma_addr_t)address;
1846 }
1847
1848 /*
1849  * The generic unmapping function for on page in the DMA address space.
1850  */
1851 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
1852                                  unsigned long address)
1853 {
1854         struct aperture_range *aperture;
1855         u64 *pte;
1856
1857         if (address >= dom->aperture_size)
1858                 return;
1859
1860         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
1861         if (!aperture)
1862                 return;
1863
1864         pte  = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
1865         if (!pte)
1866                 return;
1867
1868         pte += PM_LEVEL_INDEX(0, address);
1869
1870         WARN_ON(!*pte);
1871
1872         *pte = 0ULL;
1873 }
1874
1875 /*
1876  * This function contains common code for mapping of a physically
1877  * contiguous memory region into DMA address space. It is used by all
1878  * mapping functions provided with this IOMMU driver.
1879  * Must be called with the domain lock held.
1880  */
1881 static dma_addr_t __map_single(struct device *dev,
1882                                struct dma_ops_domain *dma_dom,
1883                                phys_addr_t paddr,
1884                                size_t size,
1885                                int dir,
1886                                bool align,
1887                                u64 dma_mask)
1888 {
1889         dma_addr_t offset = paddr & ~PAGE_MASK;
1890         dma_addr_t address, start, ret;
1891         unsigned int pages;
1892         unsigned long align_mask = 0;
1893         int i;
1894
1895         pages = iommu_num_pages(paddr, size, PAGE_SIZE);
1896         paddr &= PAGE_MASK;
1897
1898         INC_STATS_COUNTER(total_map_requests);
1899
1900         if (pages > 1)
1901                 INC_STATS_COUNTER(cross_page);
1902
1903         if (align)
1904                 align_mask = (1UL << get_order(size)) - 1;
1905
1906 retry:
1907         address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
1908                                           dma_mask);
1909         if (unlikely(address == DMA_ERROR_CODE)) {
1910                 /*
1911                  * setting next_address here will let the address
1912                  * allocator only scan the new allocated range in the
1913                  * first run. This is a small optimization.
1914                  */
1915                 dma_dom->next_address = dma_dom->aperture_size;
1916
1917                 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
1918                         goto out;
1919
1920                 /*
1921                  * aperture was successfully enlarged by 128 MB, try
1922                  * allocation again
1923                  */
1924                 goto retry;
1925         }
1926
1927         start = address;
1928         for (i = 0; i < pages; ++i) {
1929                 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
1930                 if (ret == DMA_ERROR_CODE)
1931                         goto out_unmap;
1932
1933                 paddr += PAGE_SIZE;
1934                 start += PAGE_SIZE;
1935         }
1936         address += offset;
1937
1938         ADD_STATS_COUNTER(alloced_io_mem, size);
1939
1940         if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
1941                 iommu_flush_tlb(&dma_dom->domain);
1942                 dma_dom->need_flush = false;
1943         } else if (unlikely(amd_iommu_np_cache))
1944                 iommu_flush_pages(&dma_dom->domain, address, size);
1945
1946 out:
1947         return address;
1948
1949 out_unmap:
1950
1951         for (--i; i >= 0; --i) {
1952                 start -= PAGE_SIZE;
1953                 dma_ops_domain_unmap(dma_dom, start);
1954         }
1955
1956         dma_ops_free_addresses(dma_dom, address, pages);
1957
1958         return DMA_ERROR_CODE;
1959 }
1960
1961 /*
1962  * Does the reverse of the __map_single function. Must be called with
1963  * the domain lock held too
1964  */
1965 static void __unmap_single(struct dma_ops_domain *dma_dom,
1966                            dma_addr_t dma_addr,
1967                            size_t size,
1968                            int dir)
1969 {
1970         dma_addr_t flush_addr;
1971         dma_addr_t i, start;
1972         unsigned int pages;
1973
1974         if ((dma_addr == DMA_ERROR_CODE) ||
1975             (dma_addr + size > dma_dom->aperture_size))
1976                 return;
1977
1978         flush_addr = dma_addr;
1979         pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
1980         dma_addr &= PAGE_MASK;
1981         start = dma_addr;
1982
1983         for (i = 0; i < pages; ++i) {
1984                 dma_ops_domain_unmap(dma_dom, start);
1985                 start += PAGE_SIZE;
1986         }
1987
1988         SUB_STATS_COUNTER(alloced_io_mem, size);
1989
1990         dma_ops_free_addresses(dma_dom, dma_addr, pages);
1991
1992         if (amd_iommu_unmap_flush || dma_dom->need_flush) {
1993                 iommu_flush_pages(&dma_dom->domain, flush_addr, size);
1994                 dma_dom->need_flush = false;
1995         }
1996 }
1997
1998 /*
1999  * The exported map_single function for dma_ops.
2000  */
2001 static dma_addr_t map_page(struct device *dev, struct page *page,
2002                            unsigned long offset, size_t size,
2003                            enum dma_data_direction dir,
2004                            struct dma_attrs *attrs)
2005 {
2006         unsigned long flags;
2007         struct protection_domain *domain;
2008         dma_addr_t addr;
2009         u64 dma_mask;
2010         phys_addr_t paddr = page_to_phys(page) + offset;
2011
2012         INC_STATS_COUNTER(cnt_map_single);
2013
2014         domain = get_domain(dev);
2015         if (PTR_ERR(domain) == -EINVAL)
2016                 return (dma_addr_t)paddr;
2017         else if (IS_ERR(domain))
2018                 return DMA_ERROR_CODE;
2019
2020         dma_mask = *dev->dma_mask;
2021
2022         spin_lock_irqsave(&domain->lock, flags);
2023
2024         addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2025                             dma_mask);
2026         if (addr == DMA_ERROR_CODE)
2027                 goto out;
2028
2029         iommu_flush_complete(domain);
2030
2031 out:
2032         spin_unlock_irqrestore(&domain->lock, flags);
2033
2034         return addr;
2035 }
2036
2037 /*
2038  * The exported unmap_single function for dma_ops.
2039  */
2040 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2041                        enum dma_data_direction dir, struct dma_attrs *attrs)
2042 {
2043         unsigned long flags;
2044         struct protection_domain *domain;
2045
2046         INC_STATS_COUNTER(cnt_unmap_single);
2047
2048         domain = get_domain(dev);
2049         if (IS_ERR(domain))
2050                 return;
2051
2052         spin_lock_irqsave(&domain->lock, flags);
2053
2054         __unmap_single(domain->priv, dma_addr, size, dir);
2055
2056         iommu_flush_complete(domain);
2057
2058         spin_unlock_irqrestore(&domain->lock, flags);
2059 }
2060
2061 /*
2062  * This is a special map_sg function which is used if we should map a
2063  * device which is not handled by an AMD IOMMU in the system.
2064  */
2065 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2066                            int nelems, int dir)
2067 {
2068         struct scatterlist *s;
2069         int i;
2070
2071         for_each_sg(sglist, s, nelems, i) {
2072                 s->dma_address = (dma_addr_t)sg_phys(s);
2073                 s->dma_length  = s->length;
2074         }
2075
2076         return nelems;
2077 }
2078
2079 /*
2080  * The exported map_sg function for dma_ops (handles scatter-gather
2081  * lists).
2082  */
2083 static int map_sg(struct device *dev, struct scatterlist *sglist,
2084                   int nelems, enum dma_data_direction dir,
2085                   struct dma_attrs *attrs)
2086 {
2087         unsigned long flags;
2088         struct protection_domain *domain;
2089         int i;
2090         struct scatterlist *s;
2091         phys_addr_t paddr;
2092         int mapped_elems = 0;
2093         u64 dma_mask;
2094
2095         INC_STATS_COUNTER(cnt_map_sg);
2096
2097         domain = get_domain(dev);
2098         if (PTR_ERR(domain) == -EINVAL)
2099                 return map_sg_no_iommu(dev, sglist, nelems, dir);
2100         else if (IS_ERR(domain))
2101                 return 0;
2102
2103         dma_mask = *dev->dma_mask;
2104
2105         spin_lock_irqsave(&domain->lock, flags);
2106
2107         for_each_sg(sglist, s, nelems, i) {
2108                 paddr = sg_phys(s);
2109
2110                 s->dma_address = __map_single(dev, domain->priv,
2111                                               paddr, s->length, dir, false,
2112                                               dma_mask);
2113
2114                 if (s->dma_address) {
2115                         s->dma_length = s->length;
2116                         mapped_elems++;
2117                 } else
2118                         goto unmap;
2119         }
2120
2121         iommu_flush_complete(domain);
2122
2123 out:
2124         spin_unlock_irqrestore(&domain->lock, flags);
2125
2126         return mapped_elems;
2127 unmap:
2128         for_each_sg(sglist, s, mapped_elems, i) {
2129                 if (s->dma_address)
2130                         __unmap_single(domain->priv, s->dma_address,
2131                                        s->dma_length, dir);
2132                 s->dma_address = s->dma_length = 0;
2133         }
2134
2135         mapped_elems = 0;
2136
2137         goto out;
2138 }
2139
2140 /*
2141  * The exported map_sg function for dma_ops (handles scatter-gather
2142  * lists).
2143  */
2144 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2145                      int nelems, enum dma_data_direction dir,
2146                      struct dma_attrs *attrs)
2147 {
2148         unsigned long flags;
2149         struct protection_domain *domain;
2150         struct scatterlist *s;
2151         int i;
2152
2153         INC_STATS_COUNTER(cnt_unmap_sg);
2154
2155         domain = get_domain(dev);
2156         if (IS_ERR(domain))
2157                 return;
2158
2159         spin_lock_irqsave(&domain->lock, flags);
2160
2161         for_each_sg(sglist, s, nelems, i) {
2162                 __unmap_single(domain->priv, s->dma_address,
2163                                s->dma_length, dir);
2164                 s->dma_address = s->dma_length = 0;
2165         }
2166
2167         iommu_flush_complete(domain);
2168
2169         spin_unlock_irqrestore(&domain->lock, flags);
2170 }
2171
2172 /*
2173  * The exported alloc_coherent function for dma_ops.
2174  */
2175 static void *alloc_coherent(struct device *dev, size_t size,
2176                             dma_addr_t *dma_addr, gfp_t flag)
2177 {
2178         unsigned long flags;
2179         void *virt_addr;
2180         struct protection_domain *domain;
2181         phys_addr_t paddr;
2182         u64 dma_mask = dev->coherent_dma_mask;
2183
2184         INC_STATS_COUNTER(cnt_alloc_coherent);
2185
2186         domain = get_domain(dev);
2187         if (PTR_ERR(domain) == -EINVAL) {
2188                 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2189                 *dma_addr = __pa(virt_addr);
2190                 return virt_addr;
2191         } else if (IS_ERR(domain))
2192                 return NULL;
2193
2194         dma_mask  = dev->coherent_dma_mask;
2195         flag     &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2196         flag     |= __GFP_ZERO;
2197
2198         virt_addr = (void *)__get_free_pages(flag, get_order(size));
2199         if (!virt_addr)
2200                 return NULL;
2201
2202         paddr = virt_to_phys(virt_addr);
2203
2204         if (!dma_mask)
2205                 dma_mask = *dev->dma_mask;
2206
2207         spin_lock_irqsave(&domain->lock, flags);
2208
2209         *dma_addr = __map_single(dev, domain->priv, paddr,
2210                                  size, DMA_BIDIRECTIONAL, true, dma_mask);
2211
2212         if (*dma_addr == DMA_ERROR_CODE) {
2213                 spin_unlock_irqrestore(&domain->lock, flags);
2214                 goto out_free;
2215         }
2216
2217         iommu_flush_complete(domain);
2218
2219         spin_unlock_irqrestore(&domain->lock, flags);
2220
2221         return virt_addr;
2222
2223 out_free:
2224
2225         free_pages((unsigned long)virt_addr, get_order(size));
2226
2227         return NULL;
2228 }
2229
2230 /*
2231  * The exported free_coherent function for dma_ops.
2232  */
2233 static void free_coherent(struct device *dev, size_t size,
2234                           void *virt_addr, dma_addr_t dma_addr)
2235 {
2236         unsigned long flags;
2237         struct protection_domain *domain;
2238
2239         INC_STATS_COUNTER(cnt_free_coherent);
2240
2241         domain = get_domain(dev);
2242         if (IS_ERR(domain))
2243                 goto free_mem;
2244
2245         spin_lock_irqsave(&domain->lock, flags);
2246
2247         __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2248
2249         iommu_flush_complete(domain);
2250
2251         spin_unlock_irqrestore(&domain->lock, flags);
2252
2253 free_mem:
2254         free_pages((unsigned long)virt_addr, get_order(size));
2255 }
2256
2257 /*
2258  * This function is called by the DMA layer to find out if we can handle a
2259  * particular device. It is part of the dma_ops.
2260  */
2261 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2262 {
2263         return check_device(dev);
2264 }
2265
2266 /*
2267  * The function for pre-allocating protection domains.
2268  *
2269  * If the driver core informs the DMA layer if a driver grabs a device
2270  * we don't need to preallocate the protection domains anymore.
2271  * For now we have to.
2272  */
2273 static void prealloc_protection_domains(void)
2274 {
2275         struct pci_dev *dev = NULL;
2276         struct dma_ops_domain *dma_dom;
2277         u16 devid;
2278
2279         for_each_pci_dev(dev) {
2280
2281                 /* Do we handle this device? */
2282                 if (!check_device(&dev->dev))
2283                         continue;
2284
2285                 /* Is there already any domain for it? */
2286                 if (domain_for_device(&dev->dev))
2287                         continue;
2288
2289                 devid = get_device_id(&dev->dev);
2290
2291                 dma_dom = dma_ops_domain_alloc();
2292                 if (!dma_dom)
2293                         continue;
2294                 init_unity_mappings_for_device(dma_dom, devid);
2295                 dma_dom->target_dev = devid;
2296
2297                 attach_device(&dev->dev, &dma_dom->domain);
2298
2299                 list_add_tail(&dma_dom->list, &iommu_pd_list);
2300         }
2301 }
2302
2303 static struct dma_map_ops amd_iommu_dma_ops = {
2304         .alloc_coherent = alloc_coherent,
2305         .free_coherent = free_coherent,
2306         .map_page = map_page,
2307         .unmap_page = unmap_page,
2308         .map_sg = map_sg,
2309         .unmap_sg = unmap_sg,
2310         .dma_supported = amd_iommu_dma_supported,
2311 };
2312
2313 /*
2314  * The function which clues the AMD IOMMU driver into dma_ops.
2315  */
2316
2317 void __init amd_iommu_init_api(void)
2318 {
2319         register_iommu(&amd_iommu_ops);
2320 }
2321
2322 int __init amd_iommu_init_dma_ops(void)
2323 {
2324         struct amd_iommu *iommu;
2325         int ret;
2326
2327         /*
2328          * first allocate a default protection domain for every IOMMU we
2329          * found in the system. Devices not assigned to any other
2330          * protection domain will be assigned to the default one.
2331          */
2332         for_each_iommu(iommu) {
2333                 iommu->default_dom = dma_ops_domain_alloc();
2334                 if (iommu->default_dom == NULL)
2335                         return -ENOMEM;
2336                 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
2337                 ret = iommu_init_unity_mappings(iommu);
2338                 if (ret)
2339                         goto free_domains;
2340         }
2341
2342         /*
2343          * Pre-allocate the protection domains for each device.
2344          */
2345         prealloc_protection_domains();
2346
2347         iommu_detected = 1;
2348         swiotlb = 0;
2349
2350         /* Make the driver finally visible to the drivers */
2351         dma_ops = &amd_iommu_dma_ops;
2352
2353         amd_iommu_stats_init();
2354
2355         return 0;
2356
2357 free_domains:
2358
2359         for_each_iommu(iommu) {
2360                 if (iommu->default_dom)
2361                         dma_ops_domain_free(iommu->default_dom);
2362         }
2363
2364         return ret;
2365 }
2366
2367 /*****************************************************************************
2368  *
2369  * The following functions belong to the exported interface of AMD IOMMU
2370  *
2371  * This interface allows access to lower level functions of the IOMMU
2372  * like protection domain handling and assignement of devices to domains
2373  * which is not possible with the dma_ops interface.
2374  *
2375  *****************************************************************************/
2376
2377 static void cleanup_domain(struct protection_domain *domain)
2378 {
2379         struct iommu_dev_data *dev_data, *next;
2380         unsigned long flags;
2381
2382         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2383
2384         list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
2385                 struct device *dev = dev_data->dev;
2386
2387                 __detach_device(dev);
2388                 atomic_set(&dev_data->bind, 0);
2389         }
2390
2391         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2392 }
2393
2394 static void protection_domain_free(struct protection_domain *domain)
2395 {
2396         if (!domain)
2397                 return;
2398
2399         del_domain_from_list(domain);
2400
2401         if (domain->id)
2402                 domain_id_free(domain->id);
2403
2404         kfree(domain);
2405 }
2406
2407 static struct protection_domain *protection_domain_alloc(void)
2408 {
2409         struct protection_domain *domain;
2410
2411         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2412         if (!domain)
2413                 return NULL;
2414
2415         spin_lock_init(&domain->lock);
2416         mutex_init(&domain->api_lock);
2417         domain->id = domain_id_alloc();
2418         if (!domain->id)
2419                 goto out_err;
2420         INIT_LIST_HEAD(&domain->dev_list);
2421
2422         add_domain_to_list(domain);
2423
2424         return domain;
2425
2426 out_err:
2427         kfree(domain);
2428
2429         return NULL;
2430 }
2431
2432 static int amd_iommu_domain_init(struct iommu_domain *dom)
2433 {
2434         struct protection_domain *domain;
2435
2436         domain = protection_domain_alloc();
2437         if (!domain)
2438                 goto out_free;
2439
2440         domain->mode    = PAGE_MODE_3_LEVEL;
2441         domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2442         if (!domain->pt_root)
2443                 goto out_free;
2444
2445         dom->priv = domain;
2446
2447         return 0;
2448
2449 out_free:
2450         protection_domain_free(domain);
2451
2452         return -ENOMEM;
2453 }
2454
2455 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
2456 {
2457         struct protection_domain *domain = dom->priv;
2458
2459         if (!domain)
2460                 return;
2461
2462         if (domain->dev_cnt > 0)
2463                 cleanup_domain(domain);
2464
2465         BUG_ON(domain->dev_cnt != 0);
2466
2467         free_pagetable(domain);
2468
2469         protection_domain_free(domain);
2470
2471         dom->priv = NULL;
2472 }
2473
2474 static void amd_iommu_detach_device(struct iommu_domain *dom,
2475                                     struct device *dev)
2476 {
2477         struct iommu_dev_data *dev_data = dev->archdata.iommu;
2478         struct amd_iommu *iommu;
2479         u16 devid;
2480
2481         if (!check_device(dev))
2482                 return;
2483
2484         devid = get_device_id(dev);
2485
2486         if (dev_data->domain != NULL)
2487                 detach_device(dev);
2488
2489         iommu = amd_iommu_rlookup_table[devid];
2490         if (!iommu)
2491                 return;
2492
2493         iommu_flush_device(dev);
2494         iommu_completion_wait(iommu);
2495 }
2496
2497 static int amd_iommu_attach_device(struct iommu_domain *dom,
2498                                    struct device *dev)
2499 {
2500         struct protection_domain *domain = dom->priv;
2501         struct iommu_dev_data *dev_data;
2502         struct amd_iommu *iommu;
2503         int ret;
2504         u16 devid;
2505
2506         if (!check_device(dev))
2507                 return -EINVAL;
2508
2509         dev_data = dev->archdata.iommu;
2510
2511         devid = get_device_id(dev);
2512
2513         iommu = amd_iommu_rlookup_table[devid];
2514         if (!iommu)
2515                 return -EINVAL;
2516
2517         if (dev_data->domain)
2518                 detach_device(dev);
2519
2520         ret = attach_device(dev, domain);
2521
2522         iommu_completion_wait(iommu);
2523
2524         return ret;
2525 }
2526
2527 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
2528                          phys_addr_t paddr, int gfp_order, int iommu_prot)
2529 {
2530         unsigned long page_size = 0x1000UL << gfp_order;
2531         struct protection_domain *domain = dom->priv;
2532         int prot = 0;
2533         int ret;
2534
2535         if (iommu_prot & IOMMU_READ)
2536                 prot |= IOMMU_PROT_IR;
2537         if (iommu_prot & IOMMU_WRITE)
2538                 prot |= IOMMU_PROT_IW;
2539
2540         mutex_lock(&domain->api_lock);
2541         ret = iommu_map_page(domain, iova, paddr, prot, page_size);
2542         mutex_unlock(&domain->api_lock);
2543
2544         return ret;
2545 }
2546
2547 static int amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
2548                            int gfp_order)
2549 {
2550         struct protection_domain *domain = dom->priv;
2551         unsigned long page_size, unmap_size;
2552
2553         page_size  = 0x1000UL << gfp_order;
2554
2555         mutex_lock(&domain->api_lock);
2556         unmap_size = iommu_unmap_page(domain, iova, page_size);
2557         mutex_unlock(&domain->api_lock);
2558
2559         iommu_flush_tlb_pde(domain);
2560
2561         return get_order(unmap_size);
2562 }
2563
2564 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
2565                                           unsigned long iova)
2566 {
2567         struct protection_domain *domain = dom->priv;
2568         unsigned long offset_mask;
2569         phys_addr_t paddr;
2570         u64 *pte, __pte;
2571
2572         pte = fetch_pte(domain, iova);
2573
2574         if (!pte || !IOMMU_PTE_PRESENT(*pte))
2575                 return 0;
2576
2577         if (PM_PTE_LEVEL(*pte) == 0)
2578                 offset_mask = PAGE_SIZE - 1;
2579         else
2580                 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
2581
2582         __pte = *pte & PM_ADDR_MASK;
2583         paddr = (__pte & ~offset_mask) | (iova & offset_mask);
2584
2585         return paddr;
2586 }
2587
2588 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
2589                                     unsigned long cap)
2590 {
2591         return 0;
2592 }
2593
2594 static struct iommu_ops amd_iommu_ops = {
2595         .domain_init = amd_iommu_domain_init,
2596         .domain_destroy = amd_iommu_domain_destroy,
2597         .attach_dev = amd_iommu_attach_device,
2598         .detach_dev = amd_iommu_detach_device,
2599         .map = amd_iommu_map,
2600         .unmap = amd_iommu_unmap,
2601         .iova_to_phys = amd_iommu_iova_to_phys,
2602         .domain_has_cap = amd_iommu_domain_has_cap,
2603 };
2604
2605 /*****************************************************************************
2606  *
2607  * The next functions do a basic initialization of IOMMU for pass through
2608  * mode
2609  *
2610  * In passthrough mode the IOMMU is initialized and enabled but not used for
2611  * DMA-API translation.
2612  *
2613  *****************************************************************************/
2614
2615 int __init amd_iommu_init_passthrough(void)
2616 {
2617         struct amd_iommu *iommu;
2618         struct pci_dev *dev = NULL;
2619         u16 devid;
2620
2621         /* allocate passthrough domain */
2622         pt_domain = protection_domain_alloc();
2623         if (!pt_domain)
2624                 return -ENOMEM;
2625
2626         pt_domain->mode |= PAGE_MODE_NONE;
2627
2628         while ((dev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, dev)) != NULL) {
2629
2630                 if (!check_device(&dev->dev))
2631                         continue;
2632
2633                 devid = get_device_id(&dev->dev);
2634
2635                 iommu = amd_iommu_rlookup_table[devid];
2636                 if (!iommu)
2637                         continue;
2638
2639                 attach_device(&dev->dev, pt_domain);
2640         }
2641
2642         pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
2643
2644         return 0;
2645 }