]> nv-tegra.nvidia Code Review - linux-2.6.git/blob - drivers/iommu/amd_iommu.c
iommu/amd: Add function to get IOMMUv2 domain for pdev
[linux-2.6.git] / drivers / iommu / amd_iommu.c
1 /*
2  * Copyright (C) 2007-2010 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/ratelimit.h>
21 #include <linux/pci.h>
22 #include <linux/pci-ats.h>
23 #include <linux/bitmap.h>
24 #include <linux/slab.h>
25 #include <linux/debugfs.h>
26 #include <linux/scatterlist.h>
27 #include <linux/dma-mapping.h>
28 #include <linux/iommu-helper.h>
29 #include <linux/iommu.h>
30 #include <linux/delay.h>
31 #include <linux/amd-iommu.h>
32 #include <linux/notifier.h>
33 #include <linux/export.h>
34 #include <asm/msidef.h>
35 #include <asm/proto.h>
36 #include <asm/iommu.h>
37 #include <asm/gart.h>
38 #include <asm/dma.h>
39
40 #include "amd_iommu_proto.h"
41 #include "amd_iommu_types.h"
42
43 #define CMD_SET_TYPE(cmd, t) ((cmd)->data[1] |= ((t) << 28))
44
45 #define LOOP_TIMEOUT    100000
46
47 static DEFINE_RWLOCK(amd_iommu_devtable_lock);
48
49 /* A list of preallocated protection domains */
50 static LIST_HEAD(iommu_pd_list);
51 static DEFINE_SPINLOCK(iommu_pd_list_lock);
52
53 /* List of all available dev_data structures */
54 static LIST_HEAD(dev_data_list);
55 static DEFINE_SPINLOCK(dev_data_list_lock);
56
57 /*
58  * Domain for untranslated devices - only allocated
59  * if iommu=pt passed on kernel cmd line.
60  */
61 static struct protection_domain *pt_domain;
62
63 static struct iommu_ops amd_iommu_ops;
64
65 static ATOMIC_NOTIFIER_HEAD(ppr_notifier);
66 int amd_iommu_max_glx_val = -1;
67
68 /*
69  * general struct to manage commands send to an IOMMU
70  */
71 struct iommu_cmd {
72         u32 data[4];
73 };
74
75 static void update_domain(struct protection_domain *domain);
76 static int __init alloc_passthrough_domain(void);
77
78 /****************************************************************************
79  *
80  * Helper functions
81  *
82  ****************************************************************************/
83
84 static struct iommu_dev_data *alloc_dev_data(u16 devid)
85 {
86         struct iommu_dev_data *dev_data;
87         unsigned long flags;
88
89         dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
90         if (!dev_data)
91                 return NULL;
92
93         dev_data->devid = devid;
94         atomic_set(&dev_data->bind, 0);
95
96         spin_lock_irqsave(&dev_data_list_lock, flags);
97         list_add_tail(&dev_data->dev_data_list, &dev_data_list);
98         spin_unlock_irqrestore(&dev_data_list_lock, flags);
99
100         return dev_data;
101 }
102
103 static void free_dev_data(struct iommu_dev_data *dev_data)
104 {
105         unsigned long flags;
106
107         spin_lock_irqsave(&dev_data_list_lock, flags);
108         list_del(&dev_data->dev_data_list);
109         spin_unlock_irqrestore(&dev_data_list_lock, flags);
110
111         kfree(dev_data);
112 }
113
114 static struct iommu_dev_data *search_dev_data(u16 devid)
115 {
116         struct iommu_dev_data *dev_data;
117         unsigned long flags;
118
119         spin_lock_irqsave(&dev_data_list_lock, flags);
120         list_for_each_entry(dev_data, &dev_data_list, dev_data_list) {
121                 if (dev_data->devid == devid)
122                         goto out_unlock;
123         }
124
125         dev_data = NULL;
126
127 out_unlock:
128         spin_unlock_irqrestore(&dev_data_list_lock, flags);
129
130         return dev_data;
131 }
132
133 static struct iommu_dev_data *find_dev_data(u16 devid)
134 {
135         struct iommu_dev_data *dev_data;
136
137         dev_data = search_dev_data(devid);
138
139         if (dev_data == NULL)
140                 dev_data = alloc_dev_data(devid);
141
142         return dev_data;
143 }
144
145 static inline u16 get_device_id(struct device *dev)
146 {
147         struct pci_dev *pdev = to_pci_dev(dev);
148
149         return calc_devid(pdev->bus->number, pdev->devfn);
150 }
151
152 static struct iommu_dev_data *get_dev_data(struct device *dev)
153 {
154         return dev->archdata.iommu;
155 }
156
157 static bool pci_iommuv2_capable(struct pci_dev *pdev)
158 {
159         static const int caps[] = {
160                 PCI_EXT_CAP_ID_ATS,
161                 PCI_PRI_CAP,
162                 PCI_PASID_CAP,
163         };
164         int i, pos;
165
166         for (i = 0; i < 3; ++i) {
167                 pos = pci_find_ext_capability(pdev, caps[i]);
168                 if (pos == 0)
169                         return false;
170         }
171
172         return true;
173 }
174
175 /*
176  * In this function the list of preallocated protection domains is traversed to
177  * find the domain for a specific device
178  */
179 static struct dma_ops_domain *find_protection_domain(u16 devid)
180 {
181         struct dma_ops_domain *entry, *ret = NULL;
182         unsigned long flags;
183         u16 alias = amd_iommu_alias_table[devid];
184
185         if (list_empty(&iommu_pd_list))
186                 return NULL;
187
188         spin_lock_irqsave(&iommu_pd_list_lock, flags);
189
190         list_for_each_entry(entry, &iommu_pd_list, list) {
191                 if (entry->target_dev == devid ||
192                     entry->target_dev == alias) {
193                         ret = entry;
194                         break;
195                 }
196         }
197
198         spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
199
200         return ret;
201 }
202
203 /*
204  * This function checks if the driver got a valid device from the caller to
205  * avoid dereferencing invalid pointers.
206  */
207 static bool check_device(struct device *dev)
208 {
209         u16 devid;
210
211         if (!dev || !dev->dma_mask)
212                 return false;
213
214         /* No device or no PCI device */
215         if (dev->bus != &pci_bus_type)
216                 return false;
217
218         devid = get_device_id(dev);
219
220         /* Out of our scope? */
221         if (devid > amd_iommu_last_bdf)
222                 return false;
223
224         if (amd_iommu_rlookup_table[devid] == NULL)
225                 return false;
226
227         return true;
228 }
229
230 static int iommu_init_device(struct device *dev)
231 {
232         struct pci_dev *pdev = to_pci_dev(dev);
233         struct iommu_dev_data *dev_data;
234         u16 alias;
235
236         if (dev->archdata.iommu)
237                 return 0;
238
239         dev_data = find_dev_data(get_device_id(dev));
240         if (!dev_data)
241                 return -ENOMEM;
242
243         alias = amd_iommu_alias_table[dev_data->devid];
244         if (alias != dev_data->devid) {
245                 struct iommu_dev_data *alias_data;
246
247                 alias_data = find_dev_data(alias);
248                 if (alias_data == NULL) {
249                         pr_err("AMD-Vi: Warning: Unhandled device %s\n",
250                                         dev_name(dev));
251                         free_dev_data(dev_data);
252                         return -ENOTSUPP;
253                 }
254                 dev_data->alias_data = alias_data;
255         }
256
257         if (pci_iommuv2_capable(pdev)) {
258                 struct amd_iommu *iommu;
259
260                 iommu              = amd_iommu_rlookup_table[dev_data->devid];
261                 dev_data->iommu_v2 = iommu->is_iommu_v2;
262         }
263
264         dev->archdata.iommu = dev_data;
265
266         return 0;
267 }
268
269 static void iommu_ignore_device(struct device *dev)
270 {
271         u16 devid, alias;
272
273         devid = get_device_id(dev);
274         alias = amd_iommu_alias_table[devid];
275
276         memset(&amd_iommu_dev_table[devid], 0, sizeof(struct dev_table_entry));
277         memset(&amd_iommu_dev_table[alias], 0, sizeof(struct dev_table_entry));
278
279         amd_iommu_rlookup_table[devid] = NULL;
280         amd_iommu_rlookup_table[alias] = NULL;
281 }
282
283 static void iommu_uninit_device(struct device *dev)
284 {
285         /*
286          * Nothing to do here - we keep dev_data around for unplugged devices
287          * and reuse it when the device is re-plugged - not doing so would
288          * introduce a ton of races.
289          */
290 }
291
292 void __init amd_iommu_uninit_devices(void)
293 {
294         struct iommu_dev_data *dev_data, *n;
295         struct pci_dev *pdev = NULL;
296
297         for_each_pci_dev(pdev) {
298
299                 if (!check_device(&pdev->dev))
300                         continue;
301
302                 iommu_uninit_device(&pdev->dev);
303         }
304
305         /* Free all of our dev_data structures */
306         list_for_each_entry_safe(dev_data, n, &dev_data_list, dev_data_list)
307                 free_dev_data(dev_data);
308 }
309
310 int __init amd_iommu_init_devices(void)
311 {
312         struct pci_dev *pdev = NULL;
313         int ret = 0;
314
315         for_each_pci_dev(pdev) {
316
317                 if (!check_device(&pdev->dev))
318                         continue;
319
320                 ret = iommu_init_device(&pdev->dev);
321                 if (ret == -ENOTSUPP)
322                         iommu_ignore_device(&pdev->dev);
323                 else if (ret)
324                         goto out_free;
325         }
326
327         return 0;
328
329 out_free:
330
331         amd_iommu_uninit_devices();
332
333         return ret;
334 }
335 #ifdef CONFIG_AMD_IOMMU_STATS
336
337 /*
338  * Initialization code for statistics collection
339  */
340
341 DECLARE_STATS_COUNTER(compl_wait);
342 DECLARE_STATS_COUNTER(cnt_map_single);
343 DECLARE_STATS_COUNTER(cnt_unmap_single);
344 DECLARE_STATS_COUNTER(cnt_map_sg);
345 DECLARE_STATS_COUNTER(cnt_unmap_sg);
346 DECLARE_STATS_COUNTER(cnt_alloc_coherent);
347 DECLARE_STATS_COUNTER(cnt_free_coherent);
348 DECLARE_STATS_COUNTER(cross_page);
349 DECLARE_STATS_COUNTER(domain_flush_single);
350 DECLARE_STATS_COUNTER(domain_flush_all);
351 DECLARE_STATS_COUNTER(alloced_io_mem);
352 DECLARE_STATS_COUNTER(total_map_requests);
353
354 static struct dentry *stats_dir;
355 static struct dentry *de_fflush;
356
357 static void amd_iommu_stats_add(struct __iommu_counter *cnt)
358 {
359         if (stats_dir == NULL)
360                 return;
361
362         cnt->dent = debugfs_create_u64(cnt->name, 0444, stats_dir,
363                                        &cnt->value);
364 }
365
366 static void amd_iommu_stats_init(void)
367 {
368         stats_dir = debugfs_create_dir("amd-iommu", NULL);
369         if (stats_dir == NULL)
370                 return;
371
372         de_fflush  = debugfs_create_bool("fullflush", 0444, stats_dir,
373                                          (u32 *)&amd_iommu_unmap_flush);
374
375         amd_iommu_stats_add(&compl_wait);
376         amd_iommu_stats_add(&cnt_map_single);
377         amd_iommu_stats_add(&cnt_unmap_single);
378         amd_iommu_stats_add(&cnt_map_sg);
379         amd_iommu_stats_add(&cnt_unmap_sg);
380         amd_iommu_stats_add(&cnt_alloc_coherent);
381         amd_iommu_stats_add(&cnt_free_coherent);
382         amd_iommu_stats_add(&cross_page);
383         amd_iommu_stats_add(&domain_flush_single);
384         amd_iommu_stats_add(&domain_flush_all);
385         amd_iommu_stats_add(&alloced_io_mem);
386         amd_iommu_stats_add(&total_map_requests);
387 }
388
389 #endif
390
391 /****************************************************************************
392  *
393  * Interrupt handling functions
394  *
395  ****************************************************************************/
396
397 static void dump_dte_entry(u16 devid)
398 {
399         int i;
400
401         for (i = 0; i < 4; ++i)
402                 pr_err("AMD-Vi: DTE[%d]: %016llx\n", i,
403                         amd_iommu_dev_table[devid].data[i]);
404 }
405
406 static void dump_command(unsigned long phys_addr)
407 {
408         struct iommu_cmd *cmd = phys_to_virt(phys_addr);
409         int i;
410
411         for (i = 0; i < 4; ++i)
412                 pr_err("AMD-Vi: CMD[%d]: %08x\n", i, cmd->data[i]);
413 }
414
415 static void iommu_print_event(struct amd_iommu *iommu, void *__evt)
416 {
417         u32 *event = __evt;
418         int type  = (event[1] >> EVENT_TYPE_SHIFT)  & EVENT_TYPE_MASK;
419         int devid = (event[0] >> EVENT_DEVID_SHIFT) & EVENT_DEVID_MASK;
420         int domid = (event[1] >> EVENT_DOMID_SHIFT) & EVENT_DOMID_MASK;
421         int flags = (event[1] >> EVENT_FLAGS_SHIFT) & EVENT_FLAGS_MASK;
422         u64 address = (u64)(((u64)event[3]) << 32) | event[2];
423
424         printk(KERN_ERR "AMD-Vi: Event logged [");
425
426         switch (type) {
427         case EVENT_TYPE_ILL_DEV:
428                 printk("ILLEGAL_DEV_TABLE_ENTRY device=%02x:%02x.%x "
429                        "address=0x%016llx flags=0x%04x]\n",
430                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
431                        address, flags);
432                 dump_dte_entry(devid);
433                 break;
434         case EVENT_TYPE_IO_FAULT:
435                 printk("IO_PAGE_FAULT device=%02x:%02x.%x "
436                        "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
437                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
438                        domid, address, flags);
439                 break;
440         case EVENT_TYPE_DEV_TAB_ERR:
441                 printk("DEV_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
442                        "address=0x%016llx flags=0x%04x]\n",
443                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
444                        address, flags);
445                 break;
446         case EVENT_TYPE_PAGE_TAB_ERR:
447                 printk("PAGE_TAB_HARDWARE_ERROR device=%02x:%02x.%x "
448                        "domain=0x%04x address=0x%016llx flags=0x%04x]\n",
449                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
450                        domid, address, flags);
451                 break;
452         case EVENT_TYPE_ILL_CMD:
453                 printk("ILLEGAL_COMMAND_ERROR address=0x%016llx]\n", address);
454                 dump_command(address);
455                 break;
456         case EVENT_TYPE_CMD_HARD_ERR:
457                 printk("COMMAND_HARDWARE_ERROR address=0x%016llx "
458                        "flags=0x%04x]\n", address, flags);
459                 break;
460         case EVENT_TYPE_IOTLB_INV_TO:
461                 printk("IOTLB_INV_TIMEOUT device=%02x:%02x.%x "
462                        "address=0x%016llx]\n",
463                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
464                        address);
465                 break;
466         case EVENT_TYPE_INV_DEV_REQ:
467                 printk("INVALID_DEVICE_REQUEST device=%02x:%02x.%x "
468                        "address=0x%016llx flags=0x%04x]\n",
469                        PCI_BUS(devid), PCI_SLOT(devid), PCI_FUNC(devid),
470                        address, flags);
471                 break;
472         default:
473                 printk(KERN_ERR "UNKNOWN type=0x%02x]\n", type);
474         }
475 }
476
477 static void iommu_poll_events(struct amd_iommu *iommu)
478 {
479         u32 head, tail;
480         unsigned long flags;
481
482         spin_lock_irqsave(&iommu->lock, flags);
483
484         head = readl(iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
485         tail = readl(iommu->mmio_base + MMIO_EVT_TAIL_OFFSET);
486
487         while (head != tail) {
488                 iommu_print_event(iommu, iommu->evt_buf + head);
489                 head = (head + EVENT_ENTRY_SIZE) % iommu->evt_buf_size;
490         }
491
492         writel(head, iommu->mmio_base + MMIO_EVT_HEAD_OFFSET);
493
494         spin_unlock_irqrestore(&iommu->lock, flags);
495 }
496
497 static void iommu_handle_ppr_entry(struct amd_iommu *iommu, u32 head)
498 {
499         struct amd_iommu_fault fault;
500         volatile u64 *raw;
501         int i;
502
503         raw = (u64 *)(iommu->ppr_log + head);
504
505         /*
506          * Hardware bug: Interrupt may arrive before the entry is written to
507          * memory. If this happens we need to wait for the entry to arrive.
508          */
509         for (i = 0; i < LOOP_TIMEOUT; ++i) {
510                 if (PPR_REQ_TYPE(raw[0]) != 0)
511                         break;
512                 udelay(1);
513         }
514
515         if (PPR_REQ_TYPE(raw[0]) != PPR_REQ_FAULT) {
516                 pr_err_ratelimited("AMD-Vi: Unknown PPR request received\n");
517                 return;
518         }
519
520         fault.address   = raw[1];
521         fault.pasid     = PPR_PASID(raw[0]);
522         fault.device_id = PPR_DEVID(raw[0]);
523         fault.tag       = PPR_TAG(raw[0]);
524         fault.flags     = PPR_FLAGS(raw[0]);
525
526         /*
527          * To detect the hardware bug we need to clear the entry
528          * to back to zero.
529          */
530         raw[0] = raw[1] = 0;
531
532         atomic_notifier_call_chain(&ppr_notifier, 0, &fault);
533 }
534
535 static void iommu_poll_ppr_log(struct amd_iommu *iommu)
536 {
537         unsigned long flags;
538         u32 head, tail;
539
540         if (iommu->ppr_log == NULL)
541                 return;
542
543         spin_lock_irqsave(&iommu->lock, flags);
544
545         head = readl(iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
546         tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
547
548         while (head != tail) {
549
550                 /* Handle PPR entry */
551                 iommu_handle_ppr_entry(iommu, head);
552
553                 /* Update and refresh ring-buffer state*/
554                 head = (head + PPR_ENTRY_SIZE) % PPR_LOG_SIZE;
555                 writel(head, iommu->mmio_base + MMIO_PPR_HEAD_OFFSET);
556                 tail = readl(iommu->mmio_base + MMIO_PPR_TAIL_OFFSET);
557         }
558
559         /* enable ppr interrupts again */
560         writel(MMIO_STATUS_PPR_INT_MASK, iommu->mmio_base + MMIO_STATUS_OFFSET);
561
562         spin_unlock_irqrestore(&iommu->lock, flags);
563 }
564
565 irqreturn_t amd_iommu_int_thread(int irq, void *data)
566 {
567         struct amd_iommu *iommu;
568
569         for_each_iommu(iommu) {
570                 iommu_poll_events(iommu);
571                 iommu_poll_ppr_log(iommu);
572         }
573
574         return IRQ_HANDLED;
575 }
576
577 irqreturn_t amd_iommu_int_handler(int irq, void *data)
578 {
579         return IRQ_WAKE_THREAD;
580 }
581
582 /****************************************************************************
583  *
584  * IOMMU command queuing functions
585  *
586  ****************************************************************************/
587
588 static int wait_on_sem(volatile u64 *sem)
589 {
590         int i = 0;
591
592         while (*sem == 0 && i < LOOP_TIMEOUT) {
593                 udelay(1);
594                 i += 1;
595         }
596
597         if (i == LOOP_TIMEOUT) {
598                 pr_alert("AMD-Vi: Completion-Wait loop timed out\n");
599                 return -EIO;
600         }
601
602         return 0;
603 }
604
605 static void copy_cmd_to_buffer(struct amd_iommu *iommu,
606                                struct iommu_cmd *cmd,
607                                u32 tail)
608 {
609         u8 *target;
610
611         target = iommu->cmd_buf + tail;
612         tail   = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
613
614         /* Copy command to buffer */
615         memcpy(target, cmd, sizeof(*cmd));
616
617         /* Tell the IOMMU about it */
618         writel(tail, iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
619 }
620
621 static void build_completion_wait(struct iommu_cmd *cmd, u64 address)
622 {
623         WARN_ON(address & 0x7ULL);
624
625         memset(cmd, 0, sizeof(*cmd));
626         cmd->data[0] = lower_32_bits(__pa(address)) | CMD_COMPL_WAIT_STORE_MASK;
627         cmd->data[1] = upper_32_bits(__pa(address));
628         cmd->data[2] = 1;
629         CMD_SET_TYPE(cmd, CMD_COMPL_WAIT);
630 }
631
632 static void build_inv_dte(struct iommu_cmd *cmd, u16 devid)
633 {
634         memset(cmd, 0, sizeof(*cmd));
635         cmd->data[0] = devid;
636         CMD_SET_TYPE(cmd, CMD_INV_DEV_ENTRY);
637 }
638
639 static void build_inv_iommu_pages(struct iommu_cmd *cmd, u64 address,
640                                   size_t size, u16 domid, int pde)
641 {
642         u64 pages;
643         int s;
644
645         pages = iommu_num_pages(address, size, PAGE_SIZE);
646         s     = 0;
647
648         if (pages > 1) {
649                 /*
650                  * If we have to flush more than one page, flush all
651                  * TLB entries for this domain
652                  */
653                 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
654                 s = 1;
655         }
656
657         address &= PAGE_MASK;
658
659         memset(cmd, 0, sizeof(*cmd));
660         cmd->data[1] |= domid;
661         cmd->data[2]  = lower_32_bits(address);
662         cmd->data[3]  = upper_32_bits(address);
663         CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
664         if (s) /* size bit - we flush more than one 4kb page */
665                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
666         if (pde) /* PDE bit - we wan't flush everything not only the PTEs */
667                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
668 }
669
670 static void build_inv_iotlb_pages(struct iommu_cmd *cmd, u16 devid, int qdep,
671                                   u64 address, size_t size)
672 {
673         u64 pages;
674         int s;
675
676         pages = iommu_num_pages(address, size, PAGE_SIZE);
677         s     = 0;
678
679         if (pages > 1) {
680                 /*
681                  * If we have to flush more than one page, flush all
682                  * TLB entries for this domain
683                  */
684                 address = CMD_INV_IOMMU_ALL_PAGES_ADDRESS;
685                 s = 1;
686         }
687
688         address &= PAGE_MASK;
689
690         memset(cmd, 0, sizeof(*cmd));
691         cmd->data[0]  = devid;
692         cmd->data[0] |= (qdep & 0xff) << 24;
693         cmd->data[1]  = devid;
694         cmd->data[2]  = lower_32_bits(address);
695         cmd->data[3]  = upper_32_bits(address);
696         CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
697         if (s)
698                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
699 }
700
701 static void build_inv_iommu_pasid(struct iommu_cmd *cmd, u16 domid, int pasid,
702                                   u64 address, bool size)
703 {
704         memset(cmd, 0, sizeof(*cmd));
705
706         address &= ~(0xfffULL);
707
708         cmd->data[0]  = pasid & PASID_MASK;
709         cmd->data[1]  = domid;
710         cmd->data[2]  = lower_32_bits(address);
711         cmd->data[3]  = upper_32_bits(address);
712         cmd->data[2] |= CMD_INV_IOMMU_PAGES_PDE_MASK;
713         cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
714         if (size)
715                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
716         CMD_SET_TYPE(cmd, CMD_INV_IOMMU_PAGES);
717 }
718
719 static void build_inv_iotlb_pasid(struct iommu_cmd *cmd, u16 devid, int pasid,
720                                   int qdep, u64 address, bool size)
721 {
722         memset(cmd, 0, sizeof(*cmd));
723
724         address &= ~(0xfffULL);
725
726         cmd->data[0]  = devid;
727         cmd->data[0] |= (pasid & 0xff) << 16;
728         cmd->data[0] |= (qdep  & 0xff) << 24;
729         cmd->data[1]  = devid;
730         cmd->data[1] |= ((pasid >> 8) & 0xfff) << 16;
731         cmd->data[2]  = lower_32_bits(address);
732         cmd->data[2] |= CMD_INV_IOMMU_PAGES_GN_MASK;
733         cmd->data[3]  = upper_32_bits(address);
734         if (size)
735                 cmd->data[2] |= CMD_INV_IOMMU_PAGES_SIZE_MASK;
736         CMD_SET_TYPE(cmd, CMD_INV_IOTLB_PAGES);
737 }
738
739 static void build_complete_ppr(struct iommu_cmd *cmd, u16 devid, int pasid,
740                                int status, int tag, bool gn)
741 {
742         memset(cmd, 0, sizeof(*cmd));
743
744         cmd->data[0]  = devid;
745         if (gn) {
746                 cmd->data[1]  = pasid & PASID_MASK;
747                 cmd->data[2]  = CMD_INV_IOMMU_PAGES_GN_MASK;
748         }
749         cmd->data[3]  = tag & 0x1ff;
750         cmd->data[3] |= (status & PPR_STATUS_MASK) << PPR_STATUS_SHIFT;
751
752         CMD_SET_TYPE(cmd, CMD_COMPLETE_PPR);
753 }
754
755 static void build_inv_all(struct iommu_cmd *cmd)
756 {
757         memset(cmd, 0, sizeof(*cmd));
758         CMD_SET_TYPE(cmd, CMD_INV_ALL);
759 }
760
761 /*
762  * Writes the command to the IOMMUs command buffer and informs the
763  * hardware about the new command.
764  */
765 static int iommu_queue_command_sync(struct amd_iommu *iommu,
766                                     struct iommu_cmd *cmd,
767                                     bool sync)
768 {
769         u32 left, tail, head, next_tail;
770         unsigned long flags;
771
772         WARN_ON(iommu->cmd_buf_size & CMD_BUFFER_UNINITIALIZED);
773
774 again:
775         spin_lock_irqsave(&iommu->lock, flags);
776
777         head      = readl(iommu->mmio_base + MMIO_CMD_HEAD_OFFSET);
778         tail      = readl(iommu->mmio_base + MMIO_CMD_TAIL_OFFSET);
779         next_tail = (tail + sizeof(*cmd)) % iommu->cmd_buf_size;
780         left      = (head - next_tail) % iommu->cmd_buf_size;
781
782         if (left <= 2) {
783                 struct iommu_cmd sync_cmd;
784                 volatile u64 sem = 0;
785                 int ret;
786
787                 build_completion_wait(&sync_cmd, (u64)&sem);
788                 copy_cmd_to_buffer(iommu, &sync_cmd, tail);
789
790                 spin_unlock_irqrestore(&iommu->lock, flags);
791
792                 if ((ret = wait_on_sem(&sem)) != 0)
793                         return ret;
794
795                 goto again;
796         }
797
798         copy_cmd_to_buffer(iommu, cmd, tail);
799
800         /* We need to sync now to make sure all commands are processed */
801         iommu->need_sync = sync;
802
803         spin_unlock_irqrestore(&iommu->lock, flags);
804
805         return 0;
806 }
807
808 static int iommu_queue_command(struct amd_iommu *iommu, struct iommu_cmd *cmd)
809 {
810         return iommu_queue_command_sync(iommu, cmd, true);
811 }
812
813 /*
814  * This function queues a completion wait command into the command
815  * buffer of an IOMMU
816  */
817 static int iommu_completion_wait(struct amd_iommu *iommu)
818 {
819         struct iommu_cmd cmd;
820         volatile u64 sem = 0;
821         int ret;
822
823         if (!iommu->need_sync)
824                 return 0;
825
826         build_completion_wait(&cmd, (u64)&sem);
827
828         ret = iommu_queue_command_sync(iommu, &cmd, false);
829         if (ret)
830                 return ret;
831
832         return wait_on_sem(&sem);
833 }
834
835 static int iommu_flush_dte(struct amd_iommu *iommu, u16 devid)
836 {
837         struct iommu_cmd cmd;
838
839         build_inv_dte(&cmd, devid);
840
841         return iommu_queue_command(iommu, &cmd);
842 }
843
844 static void iommu_flush_dte_all(struct amd_iommu *iommu)
845 {
846         u32 devid;
847
848         for (devid = 0; devid <= 0xffff; ++devid)
849                 iommu_flush_dte(iommu, devid);
850
851         iommu_completion_wait(iommu);
852 }
853
854 /*
855  * This function uses heavy locking and may disable irqs for some time. But
856  * this is no issue because it is only called during resume.
857  */
858 static void iommu_flush_tlb_all(struct amd_iommu *iommu)
859 {
860         u32 dom_id;
861
862         for (dom_id = 0; dom_id <= 0xffff; ++dom_id) {
863                 struct iommu_cmd cmd;
864                 build_inv_iommu_pages(&cmd, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
865                                       dom_id, 1);
866                 iommu_queue_command(iommu, &cmd);
867         }
868
869         iommu_completion_wait(iommu);
870 }
871
872 static void iommu_flush_all(struct amd_iommu *iommu)
873 {
874         struct iommu_cmd cmd;
875
876         build_inv_all(&cmd);
877
878         iommu_queue_command(iommu, &cmd);
879         iommu_completion_wait(iommu);
880 }
881
882 void iommu_flush_all_caches(struct amd_iommu *iommu)
883 {
884         if (iommu_feature(iommu, FEATURE_IA)) {
885                 iommu_flush_all(iommu);
886         } else {
887                 iommu_flush_dte_all(iommu);
888                 iommu_flush_tlb_all(iommu);
889         }
890 }
891
892 /*
893  * Command send function for flushing on-device TLB
894  */
895 static int device_flush_iotlb(struct iommu_dev_data *dev_data,
896                               u64 address, size_t size)
897 {
898         struct amd_iommu *iommu;
899         struct iommu_cmd cmd;
900         int qdep;
901
902         qdep     = dev_data->ats.qdep;
903         iommu    = amd_iommu_rlookup_table[dev_data->devid];
904
905         build_inv_iotlb_pages(&cmd, dev_data->devid, qdep, address, size);
906
907         return iommu_queue_command(iommu, &cmd);
908 }
909
910 /*
911  * Command send function for invalidating a device table entry
912  */
913 static int device_flush_dte(struct iommu_dev_data *dev_data)
914 {
915         struct amd_iommu *iommu;
916         int ret;
917
918         iommu = amd_iommu_rlookup_table[dev_data->devid];
919
920         ret = iommu_flush_dte(iommu, dev_data->devid);
921         if (ret)
922                 return ret;
923
924         if (dev_data->ats.enabled)
925                 ret = device_flush_iotlb(dev_data, 0, ~0UL);
926
927         return ret;
928 }
929
930 /*
931  * TLB invalidation function which is called from the mapping functions.
932  * It invalidates a single PTE if the range to flush is within a single
933  * page. Otherwise it flushes the whole TLB of the IOMMU.
934  */
935 static void __domain_flush_pages(struct protection_domain *domain,
936                                  u64 address, size_t size, int pde)
937 {
938         struct iommu_dev_data *dev_data;
939         struct iommu_cmd cmd;
940         int ret = 0, i;
941
942         build_inv_iommu_pages(&cmd, address, size, domain->id, pde);
943
944         for (i = 0; i < amd_iommus_present; ++i) {
945                 if (!domain->dev_iommu[i])
946                         continue;
947
948                 /*
949                  * Devices of this domain are behind this IOMMU
950                  * We need a TLB flush
951                  */
952                 ret |= iommu_queue_command(amd_iommus[i], &cmd);
953         }
954
955         list_for_each_entry(dev_data, &domain->dev_list, list) {
956
957                 if (!dev_data->ats.enabled)
958                         continue;
959
960                 ret |= device_flush_iotlb(dev_data, address, size);
961         }
962
963         WARN_ON(ret);
964 }
965
966 static void domain_flush_pages(struct protection_domain *domain,
967                                u64 address, size_t size)
968 {
969         __domain_flush_pages(domain, address, size, 0);
970 }
971
972 /* Flush the whole IO/TLB for a given protection domain */
973 static void domain_flush_tlb(struct protection_domain *domain)
974 {
975         __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 0);
976 }
977
978 /* Flush the whole IO/TLB for a given protection domain - including PDE */
979 static void domain_flush_tlb_pde(struct protection_domain *domain)
980 {
981         __domain_flush_pages(domain, 0, CMD_INV_IOMMU_ALL_PAGES_ADDRESS, 1);
982 }
983
984 static void domain_flush_complete(struct protection_domain *domain)
985 {
986         int i;
987
988         for (i = 0; i < amd_iommus_present; ++i) {
989                 if (!domain->dev_iommu[i])
990                         continue;
991
992                 /*
993                  * Devices of this domain are behind this IOMMU
994                  * We need to wait for completion of all commands.
995                  */
996                 iommu_completion_wait(amd_iommus[i]);
997         }
998 }
999
1000
1001 /*
1002  * This function flushes the DTEs for all devices in domain
1003  */
1004 static void domain_flush_devices(struct protection_domain *domain)
1005 {
1006         struct iommu_dev_data *dev_data;
1007
1008         list_for_each_entry(dev_data, &domain->dev_list, list)
1009                 device_flush_dte(dev_data);
1010 }
1011
1012 /****************************************************************************
1013  *
1014  * The functions below are used the create the page table mappings for
1015  * unity mapped regions.
1016  *
1017  ****************************************************************************/
1018
1019 /*
1020  * This function is used to add another level to an IO page table. Adding
1021  * another level increases the size of the address space by 9 bits to a size up
1022  * to 64 bits.
1023  */
1024 static bool increase_address_space(struct protection_domain *domain,
1025                                    gfp_t gfp)
1026 {
1027         u64 *pte;
1028
1029         if (domain->mode == PAGE_MODE_6_LEVEL)
1030                 /* address space already 64 bit large */
1031                 return false;
1032
1033         pte = (void *)get_zeroed_page(gfp);
1034         if (!pte)
1035                 return false;
1036
1037         *pte             = PM_LEVEL_PDE(domain->mode,
1038                                         virt_to_phys(domain->pt_root));
1039         domain->pt_root  = pte;
1040         domain->mode    += 1;
1041         domain->updated  = true;
1042
1043         return true;
1044 }
1045
1046 static u64 *alloc_pte(struct protection_domain *domain,
1047                       unsigned long address,
1048                       unsigned long page_size,
1049                       u64 **pte_page,
1050                       gfp_t gfp)
1051 {
1052         int level, end_lvl;
1053         u64 *pte, *page;
1054
1055         BUG_ON(!is_power_of_2(page_size));
1056
1057         while (address > PM_LEVEL_SIZE(domain->mode))
1058                 increase_address_space(domain, gfp);
1059
1060         level   = domain->mode - 1;
1061         pte     = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1062         address = PAGE_SIZE_ALIGN(address, page_size);
1063         end_lvl = PAGE_SIZE_LEVEL(page_size);
1064
1065         while (level > end_lvl) {
1066                 if (!IOMMU_PTE_PRESENT(*pte)) {
1067                         page = (u64 *)get_zeroed_page(gfp);
1068                         if (!page)
1069                                 return NULL;
1070                         *pte = PM_LEVEL_PDE(level, virt_to_phys(page));
1071                 }
1072
1073                 /* No level skipping support yet */
1074                 if (PM_PTE_LEVEL(*pte) != level)
1075                         return NULL;
1076
1077                 level -= 1;
1078
1079                 pte = IOMMU_PTE_PAGE(*pte);
1080
1081                 if (pte_page && level == end_lvl)
1082                         *pte_page = pte;
1083
1084                 pte = &pte[PM_LEVEL_INDEX(level, address)];
1085         }
1086
1087         return pte;
1088 }
1089
1090 /*
1091  * This function checks if there is a PTE for a given dma address. If
1092  * there is one, it returns the pointer to it.
1093  */
1094 static u64 *fetch_pte(struct protection_domain *domain, unsigned long address)
1095 {
1096         int level;
1097         u64 *pte;
1098
1099         if (address > PM_LEVEL_SIZE(domain->mode))
1100                 return NULL;
1101
1102         level   =  domain->mode - 1;
1103         pte     = &domain->pt_root[PM_LEVEL_INDEX(level, address)];
1104
1105         while (level > 0) {
1106
1107                 /* Not Present */
1108                 if (!IOMMU_PTE_PRESENT(*pte))
1109                         return NULL;
1110
1111                 /* Large PTE */
1112                 if (PM_PTE_LEVEL(*pte) == 0x07) {
1113                         unsigned long pte_mask, __pte;
1114
1115                         /*
1116                          * If we have a series of large PTEs, make
1117                          * sure to return a pointer to the first one.
1118                          */
1119                         pte_mask = PTE_PAGE_SIZE(*pte);
1120                         pte_mask = ~((PAGE_SIZE_PTE_COUNT(pte_mask) << 3) - 1);
1121                         __pte    = ((unsigned long)pte) & pte_mask;
1122
1123                         return (u64 *)__pte;
1124                 }
1125
1126                 /* No level skipping support yet */
1127                 if (PM_PTE_LEVEL(*pte) != level)
1128                         return NULL;
1129
1130                 level -= 1;
1131
1132                 /* Walk to the next level */
1133                 pte = IOMMU_PTE_PAGE(*pte);
1134                 pte = &pte[PM_LEVEL_INDEX(level, address)];
1135         }
1136
1137         return pte;
1138 }
1139
1140 /*
1141  * Generic mapping functions. It maps a physical address into a DMA
1142  * address space. It allocates the page table pages if necessary.
1143  * In the future it can be extended to a generic mapping function
1144  * supporting all features of AMD IOMMU page tables like level skipping
1145  * and full 64 bit address spaces.
1146  */
1147 static int iommu_map_page(struct protection_domain *dom,
1148                           unsigned long bus_addr,
1149                           unsigned long phys_addr,
1150                           int prot,
1151                           unsigned long page_size)
1152 {
1153         u64 __pte, *pte;
1154         int i, count;
1155
1156         if (!(prot & IOMMU_PROT_MASK))
1157                 return -EINVAL;
1158
1159         bus_addr  = PAGE_ALIGN(bus_addr);
1160         phys_addr = PAGE_ALIGN(phys_addr);
1161         count     = PAGE_SIZE_PTE_COUNT(page_size);
1162         pte       = alloc_pte(dom, bus_addr, page_size, NULL, GFP_KERNEL);
1163
1164         for (i = 0; i < count; ++i)
1165                 if (IOMMU_PTE_PRESENT(pte[i]))
1166                         return -EBUSY;
1167
1168         if (page_size > PAGE_SIZE) {
1169                 __pte = PAGE_SIZE_PTE(phys_addr, page_size);
1170                 __pte |= PM_LEVEL_ENC(7) | IOMMU_PTE_P | IOMMU_PTE_FC;
1171         } else
1172                 __pte = phys_addr | IOMMU_PTE_P | IOMMU_PTE_FC;
1173
1174         if (prot & IOMMU_PROT_IR)
1175                 __pte |= IOMMU_PTE_IR;
1176         if (prot & IOMMU_PROT_IW)
1177                 __pte |= IOMMU_PTE_IW;
1178
1179         for (i = 0; i < count; ++i)
1180                 pte[i] = __pte;
1181
1182         update_domain(dom);
1183
1184         return 0;
1185 }
1186
1187 static unsigned long iommu_unmap_page(struct protection_domain *dom,
1188                                       unsigned long bus_addr,
1189                                       unsigned long page_size)
1190 {
1191         unsigned long long unmap_size, unmapped;
1192         u64 *pte;
1193
1194         BUG_ON(!is_power_of_2(page_size));
1195
1196         unmapped = 0;
1197
1198         while (unmapped < page_size) {
1199
1200                 pte = fetch_pte(dom, bus_addr);
1201
1202                 if (!pte) {
1203                         /*
1204                          * No PTE for this address
1205                          * move forward in 4kb steps
1206                          */
1207                         unmap_size = PAGE_SIZE;
1208                 } else if (PM_PTE_LEVEL(*pte) == 0) {
1209                         /* 4kb PTE found for this address */
1210                         unmap_size = PAGE_SIZE;
1211                         *pte       = 0ULL;
1212                 } else {
1213                         int count, i;
1214
1215                         /* Large PTE found which maps this address */
1216                         unmap_size = PTE_PAGE_SIZE(*pte);
1217                         count      = PAGE_SIZE_PTE_COUNT(unmap_size);
1218                         for (i = 0; i < count; i++)
1219                                 pte[i] = 0ULL;
1220                 }
1221
1222                 bus_addr  = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1223                 unmapped += unmap_size;
1224         }
1225
1226         BUG_ON(!is_power_of_2(unmapped));
1227
1228         return unmapped;
1229 }
1230
1231 /*
1232  * This function checks if a specific unity mapping entry is needed for
1233  * this specific IOMMU.
1234  */
1235 static int iommu_for_unity_map(struct amd_iommu *iommu,
1236                                struct unity_map_entry *entry)
1237 {
1238         u16 bdf, i;
1239
1240         for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1241                 bdf = amd_iommu_alias_table[i];
1242                 if (amd_iommu_rlookup_table[bdf] == iommu)
1243                         return 1;
1244         }
1245
1246         return 0;
1247 }
1248
1249 /*
1250  * This function actually applies the mapping to the page table of the
1251  * dma_ops domain.
1252  */
1253 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1254                              struct unity_map_entry *e)
1255 {
1256         u64 addr;
1257         int ret;
1258
1259         for (addr = e->address_start; addr < e->address_end;
1260              addr += PAGE_SIZE) {
1261                 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1262                                      PAGE_SIZE);
1263                 if (ret)
1264                         return ret;
1265                 /*
1266                  * if unity mapping is in aperture range mark the page
1267                  * as allocated in the aperture
1268                  */
1269                 if (addr < dma_dom->aperture_size)
1270                         __set_bit(addr >> PAGE_SHIFT,
1271                                   dma_dom->aperture[0]->bitmap);
1272         }
1273
1274         return 0;
1275 }
1276
1277 /*
1278  * Init the unity mappings for a specific IOMMU in the system
1279  *
1280  * Basically iterates over all unity mapping entries and applies them to
1281  * the default domain DMA of that IOMMU if necessary.
1282  */
1283 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1284 {
1285         struct unity_map_entry *entry;
1286         int ret;
1287
1288         list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1289                 if (!iommu_for_unity_map(iommu, entry))
1290                         continue;
1291                 ret = dma_ops_unity_map(iommu->default_dom, entry);
1292                 if (ret)
1293                         return ret;
1294         }
1295
1296         return 0;
1297 }
1298
1299 /*
1300  * Inits the unity mappings required for a specific device
1301  */
1302 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1303                                           u16 devid)
1304 {
1305         struct unity_map_entry *e;
1306         int ret;
1307
1308         list_for_each_entry(e, &amd_iommu_unity_map, list) {
1309                 if (!(devid >= e->devid_start && devid <= e->devid_end))
1310                         continue;
1311                 ret = dma_ops_unity_map(dma_dom, e);
1312                 if (ret)
1313                         return ret;
1314         }
1315
1316         return 0;
1317 }
1318
1319 /****************************************************************************
1320  *
1321  * The next functions belong to the address allocator for the dma_ops
1322  * interface functions. They work like the allocators in the other IOMMU
1323  * drivers. Its basically a bitmap which marks the allocated pages in
1324  * the aperture. Maybe it could be enhanced in the future to a more
1325  * efficient allocator.
1326  *
1327  ****************************************************************************/
1328
1329 /*
1330  * The address allocator core functions.
1331  *
1332  * called with domain->lock held
1333  */
1334
1335 /*
1336  * Used to reserve address ranges in the aperture (e.g. for exclusion
1337  * ranges.
1338  */
1339 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1340                                       unsigned long start_page,
1341                                       unsigned int pages)
1342 {
1343         unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1344
1345         if (start_page + pages > last_page)
1346                 pages = last_page - start_page;
1347
1348         for (i = start_page; i < start_page + pages; ++i) {
1349                 int index = i / APERTURE_RANGE_PAGES;
1350                 int page  = i % APERTURE_RANGE_PAGES;
1351                 __set_bit(page, dom->aperture[index]->bitmap);
1352         }
1353 }
1354
1355 /*
1356  * This function is used to add a new aperture range to an existing
1357  * aperture in case of dma_ops domain allocation or address allocation
1358  * failure.
1359  */
1360 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1361                            bool populate, gfp_t gfp)
1362 {
1363         int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1364         struct amd_iommu *iommu;
1365         unsigned long i, old_size;
1366
1367 #ifdef CONFIG_IOMMU_STRESS
1368         populate = false;
1369 #endif
1370
1371         if (index >= APERTURE_MAX_RANGES)
1372                 return -ENOMEM;
1373
1374         dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1375         if (!dma_dom->aperture[index])
1376                 return -ENOMEM;
1377
1378         dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1379         if (!dma_dom->aperture[index]->bitmap)
1380                 goto out_free;
1381
1382         dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1383
1384         if (populate) {
1385                 unsigned long address = dma_dom->aperture_size;
1386                 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1387                 u64 *pte, *pte_page;
1388
1389                 for (i = 0; i < num_ptes; ++i) {
1390                         pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1391                                         &pte_page, gfp);
1392                         if (!pte)
1393                                 goto out_free;
1394
1395                         dma_dom->aperture[index]->pte_pages[i] = pte_page;
1396
1397                         address += APERTURE_RANGE_SIZE / 64;
1398                 }
1399         }
1400
1401         old_size                = dma_dom->aperture_size;
1402         dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1403
1404         /* Reserve address range used for MSI messages */
1405         if (old_size < MSI_ADDR_BASE_LO &&
1406             dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1407                 unsigned long spage;
1408                 int pages;
1409
1410                 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1411                 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1412
1413                 dma_ops_reserve_addresses(dma_dom, spage, pages);
1414         }
1415
1416         /* Initialize the exclusion range if necessary */
1417         for_each_iommu(iommu) {
1418                 if (iommu->exclusion_start &&
1419                     iommu->exclusion_start >= dma_dom->aperture[index]->offset
1420                     && iommu->exclusion_start < dma_dom->aperture_size) {
1421                         unsigned long startpage;
1422                         int pages = iommu_num_pages(iommu->exclusion_start,
1423                                                     iommu->exclusion_length,
1424                                                     PAGE_SIZE);
1425                         startpage = iommu->exclusion_start >> PAGE_SHIFT;
1426                         dma_ops_reserve_addresses(dma_dom, startpage, pages);
1427                 }
1428         }
1429
1430         /*
1431          * Check for areas already mapped as present in the new aperture
1432          * range and mark those pages as reserved in the allocator. Such
1433          * mappings may already exist as a result of requested unity
1434          * mappings for devices.
1435          */
1436         for (i = dma_dom->aperture[index]->offset;
1437              i < dma_dom->aperture_size;
1438              i += PAGE_SIZE) {
1439                 u64 *pte = fetch_pte(&dma_dom->domain, i);
1440                 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1441                         continue;
1442
1443                 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1444         }
1445
1446         update_domain(&dma_dom->domain);
1447
1448         return 0;
1449
1450 out_free:
1451         update_domain(&dma_dom->domain);
1452
1453         free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1454
1455         kfree(dma_dom->aperture[index]);
1456         dma_dom->aperture[index] = NULL;
1457
1458         return -ENOMEM;
1459 }
1460
1461 static unsigned long dma_ops_area_alloc(struct device *dev,
1462                                         struct dma_ops_domain *dom,
1463                                         unsigned int pages,
1464                                         unsigned long align_mask,
1465                                         u64 dma_mask,
1466                                         unsigned long start)
1467 {
1468         unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1469         int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1470         int i = start >> APERTURE_RANGE_SHIFT;
1471         unsigned long boundary_size;
1472         unsigned long address = -1;
1473         unsigned long limit;
1474
1475         next_bit >>= PAGE_SHIFT;
1476
1477         boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1478                         PAGE_SIZE) >> PAGE_SHIFT;
1479
1480         for (;i < max_index; ++i) {
1481                 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1482
1483                 if (dom->aperture[i]->offset >= dma_mask)
1484                         break;
1485
1486                 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1487                                                dma_mask >> PAGE_SHIFT);
1488
1489                 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1490                                            limit, next_bit, pages, 0,
1491                                             boundary_size, align_mask);
1492                 if (address != -1) {
1493                         address = dom->aperture[i]->offset +
1494                                   (address << PAGE_SHIFT);
1495                         dom->next_address = address + (pages << PAGE_SHIFT);
1496                         break;
1497                 }
1498
1499                 next_bit = 0;
1500         }
1501
1502         return address;
1503 }
1504
1505 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1506                                              struct dma_ops_domain *dom,
1507                                              unsigned int pages,
1508                                              unsigned long align_mask,
1509                                              u64 dma_mask)
1510 {
1511         unsigned long address;
1512
1513 #ifdef CONFIG_IOMMU_STRESS
1514         dom->next_address = 0;
1515         dom->need_flush = true;
1516 #endif
1517
1518         address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1519                                      dma_mask, dom->next_address);
1520
1521         if (address == -1) {
1522                 dom->next_address = 0;
1523                 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1524                                              dma_mask, 0);
1525                 dom->need_flush = true;
1526         }
1527
1528         if (unlikely(address == -1))
1529                 address = DMA_ERROR_CODE;
1530
1531         WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1532
1533         return address;
1534 }
1535
1536 /*
1537  * The address free function.
1538  *
1539  * called with domain->lock held
1540  */
1541 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1542                                    unsigned long address,
1543                                    unsigned int pages)
1544 {
1545         unsigned i = address >> APERTURE_RANGE_SHIFT;
1546         struct aperture_range *range = dom->aperture[i];
1547
1548         BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1549
1550 #ifdef CONFIG_IOMMU_STRESS
1551         if (i < 4)
1552                 return;
1553 #endif
1554
1555         if (address >= dom->next_address)
1556                 dom->need_flush = true;
1557
1558         address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1559
1560         bitmap_clear(range->bitmap, address, pages);
1561
1562 }
1563
1564 /****************************************************************************
1565  *
1566  * The next functions belong to the domain allocation. A domain is
1567  * allocated for every IOMMU as the default domain. If device isolation
1568  * is enabled, every device get its own domain. The most important thing
1569  * about domains is the page table mapping the DMA address space they
1570  * contain.
1571  *
1572  ****************************************************************************/
1573
1574 /*
1575  * This function adds a protection domain to the global protection domain list
1576  */
1577 static void add_domain_to_list(struct protection_domain *domain)
1578 {
1579         unsigned long flags;
1580
1581         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1582         list_add(&domain->list, &amd_iommu_pd_list);
1583         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1584 }
1585
1586 /*
1587  * This function removes a protection domain to the global
1588  * protection domain list
1589  */
1590 static void del_domain_from_list(struct protection_domain *domain)
1591 {
1592         unsigned long flags;
1593
1594         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1595         list_del(&domain->list);
1596         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1597 }
1598
1599 static u16 domain_id_alloc(void)
1600 {
1601         unsigned long flags;
1602         int id;
1603
1604         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1605         id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1606         BUG_ON(id == 0);
1607         if (id > 0 && id < MAX_DOMAIN_ID)
1608                 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1609         else
1610                 id = 0;
1611         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1612
1613         return id;
1614 }
1615
1616 static void domain_id_free(int id)
1617 {
1618         unsigned long flags;
1619
1620         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1621         if (id > 0 && id < MAX_DOMAIN_ID)
1622                 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1623         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1624 }
1625
1626 static void free_pagetable(struct protection_domain *domain)
1627 {
1628         int i, j;
1629         u64 *p1, *p2, *p3;
1630
1631         p1 = domain->pt_root;
1632
1633         if (!p1)
1634                 return;
1635
1636         for (i = 0; i < 512; ++i) {
1637                 if (!IOMMU_PTE_PRESENT(p1[i]))
1638                         continue;
1639
1640                 p2 = IOMMU_PTE_PAGE(p1[i]);
1641                 for (j = 0; j < 512; ++j) {
1642                         if (!IOMMU_PTE_PRESENT(p2[j]))
1643                                 continue;
1644                         p3 = IOMMU_PTE_PAGE(p2[j]);
1645                         free_page((unsigned long)p3);
1646                 }
1647
1648                 free_page((unsigned long)p2);
1649         }
1650
1651         free_page((unsigned long)p1);
1652
1653         domain->pt_root = NULL;
1654 }
1655
1656 static void free_gcr3_tbl_level1(u64 *tbl)
1657 {
1658         u64 *ptr;
1659         int i;
1660
1661         for (i = 0; i < 512; ++i) {
1662                 if (!(tbl[i] & GCR3_VALID))
1663                         continue;
1664
1665                 ptr = __va(tbl[i] & PAGE_MASK);
1666
1667                 free_page((unsigned long)ptr);
1668         }
1669 }
1670
1671 static void free_gcr3_tbl_level2(u64 *tbl)
1672 {
1673         u64 *ptr;
1674         int i;
1675
1676         for (i = 0; i < 512; ++i) {
1677                 if (!(tbl[i] & GCR3_VALID))
1678                         continue;
1679
1680                 ptr = __va(tbl[i] & PAGE_MASK);
1681
1682                 free_gcr3_tbl_level1(ptr);
1683         }
1684 }
1685
1686 static void free_gcr3_table(struct protection_domain *domain)
1687 {
1688         if (domain->glx == 2)
1689                 free_gcr3_tbl_level2(domain->gcr3_tbl);
1690         else if (domain->glx == 1)
1691                 free_gcr3_tbl_level1(domain->gcr3_tbl);
1692         else if (domain->glx != 0)
1693                 BUG();
1694
1695         free_page((unsigned long)domain->gcr3_tbl);
1696 }
1697
1698 /*
1699  * Free a domain, only used if something went wrong in the
1700  * allocation path and we need to free an already allocated page table
1701  */
1702 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1703 {
1704         int i;
1705
1706         if (!dom)
1707                 return;
1708
1709         del_domain_from_list(&dom->domain);
1710
1711         free_pagetable(&dom->domain);
1712
1713         for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1714                 if (!dom->aperture[i])
1715                         continue;
1716                 free_page((unsigned long)dom->aperture[i]->bitmap);
1717                 kfree(dom->aperture[i]);
1718         }
1719
1720         kfree(dom);
1721 }
1722
1723 /*
1724  * Allocates a new protection domain usable for the dma_ops functions.
1725  * It also initializes the page table and the address allocator data
1726  * structures required for the dma_ops interface
1727  */
1728 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1729 {
1730         struct dma_ops_domain *dma_dom;
1731
1732         dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1733         if (!dma_dom)
1734                 return NULL;
1735
1736         spin_lock_init(&dma_dom->domain.lock);
1737
1738         dma_dom->domain.id = domain_id_alloc();
1739         if (dma_dom->domain.id == 0)
1740                 goto free_dma_dom;
1741         INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1742         dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1743         dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1744         dma_dom->domain.flags = PD_DMA_OPS_MASK;
1745         dma_dom->domain.priv = dma_dom;
1746         if (!dma_dom->domain.pt_root)
1747                 goto free_dma_dom;
1748
1749         dma_dom->need_flush = false;
1750         dma_dom->target_dev = 0xffff;
1751
1752         add_domain_to_list(&dma_dom->domain);
1753
1754         if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1755                 goto free_dma_dom;
1756
1757         /*
1758          * mark the first page as allocated so we never return 0 as
1759          * a valid dma-address. So we can use 0 as error value
1760          */
1761         dma_dom->aperture[0]->bitmap[0] = 1;
1762         dma_dom->next_address = 0;
1763
1764
1765         return dma_dom;
1766
1767 free_dma_dom:
1768         dma_ops_domain_free(dma_dom);
1769
1770         return NULL;
1771 }
1772
1773 /*
1774  * little helper function to check whether a given protection domain is a
1775  * dma_ops domain
1776  */
1777 static bool dma_ops_domain(struct protection_domain *domain)
1778 {
1779         return domain->flags & PD_DMA_OPS_MASK;
1780 }
1781
1782 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1783 {
1784         u64 pte_root = 0;
1785         u64 flags = 0;
1786
1787         if (domain->mode != PAGE_MODE_NONE)
1788                 pte_root = virt_to_phys(domain->pt_root);
1789
1790         pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1791                     << DEV_ENTRY_MODE_SHIFT;
1792         pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1793
1794         flags = amd_iommu_dev_table[devid].data[1];
1795
1796         if (ats)
1797                 flags |= DTE_FLAG_IOTLB;
1798
1799         if (domain->flags & PD_IOMMUV2_MASK) {
1800                 u64 gcr3 = __pa(domain->gcr3_tbl);
1801                 u64 glx  = domain->glx;
1802                 u64 tmp;
1803
1804                 pte_root |= DTE_FLAG_GV;
1805                 pte_root |= (glx & DTE_GLX_MASK) << DTE_GLX_SHIFT;
1806
1807                 /* First mask out possible old values for GCR3 table */
1808                 tmp = DTE_GCR3_VAL_B(~0ULL) << DTE_GCR3_SHIFT_B;
1809                 flags    &= ~tmp;
1810
1811                 tmp = DTE_GCR3_VAL_C(~0ULL) << DTE_GCR3_SHIFT_C;
1812                 flags    &= ~tmp;
1813
1814                 /* Encode GCR3 table into DTE */
1815                 tmp = DTE_GCR3_VAL_A(gcr3) << DTE_GCR3_SHIFT_A;
1816                 pte_root |= tmp;
1817
1818                 tmp = DTE_GCR3_VAL_B(gcr3) << DTE_GCR3_SHIFT_B;
1819                 flags    |= tmp;
1820
1821                 tmp = DTE_GCR3_VAL_C(gcr3) << DTE_GCR3_SHIFT_C;
1822                 flags    |= tmp;
1823         }
1824
1825         flags &= ~(0xffffUL);
1826         flags |= domain->id;
1827
1828         amd_iommu_dev_table[devid].data[1]  = flags;
1829         amd_iommu_dev_table[devid].data[0]  = pte_root;
1830 }
1831
1832 static void clear_dte_entry(u16 devid)
1833 {
1834         /* remove entry from the device table seen by the hardware */
1835         amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1836         amd_iommu_dev_table[devid].data[1] = 0;
1837
1838         amd_iommu_apply_erratum_63(devid);
1839 }
1840
1841 static void do_attach(struct iommu_dev_data *dev_data,
1842                       struct protection_domain *domain)
1843 {
1844         struct amd_iommu *iommu;
1845         bool ats;
1846
1847         iommu = amd_iommu_rlookup_table[dev_data->devid];
1848         ats   = dev_data->ats.enabled;
1849
1850         /* Update data structures */
1851         dev_data->domain = domain;
1852         list_add(&dev_data->list, &domain->dev_list);
1853         set_dte_entry(dev_data->devid, domain, ats);
1854
1855         /* Do reference counting */
1856         domain->dev_iommu[iommu->index] += 1;
1857         domain->dev_cnt                 += 1;
1858
1859         /* Flush the DTE entry */
1860         device_flush_dte(dev_data);
1861 }
1862
1863 static void do_detach(struct iommu_dev_data *dev_data)
1864 {
1865         struct amd_iommu *iommu;
1866
1867         iommu = amd_iommu_rlookup_table[dev_data->devid];
1868
1869         /* decrease reference counters */
1870         dev_data->domain->dev_iommu[iommu->index] -= 1;
1871         dev_data->domain->dev_cnt                 -= 1;
1872
1873         /* Update data structures */
1874         dev_data->domain = NULL;
1875         list_del(&dev_data->list);
1876         clear_dte_entry(dev_data->devid);
1877
1878         /* Flush the DTE entry */
1879         device_flush_dte(dev_data);
1880 }
1881
1882 /*
1883  * If a device is not yet associated with a domain, this function does
1884  * assigns it visible for the hardware
1885  */
1886 static int __attach_device(struct iommu_dev_data *dev_data,
1887                            struct protection_domain *domain)
1888 {
1889         int ret;
1890
1891         /* lock domain */
1892         spin_lock(&domain->lock);
1893
1894         if (dev_data->alias_data != NULL) {
1895                 struct iommu_dev_data *alias_data = dev_data->alias_data;
1896
1897                 /* Some sanity checks */
1898                 ret = -EBUSY;
1899                 if (alias_data->domain != NULL &&
1900                                 alias_data->domain != domain)
1901                         goto out_unlock;
1902
1903                 if (dev_data->domain != NULL &&
1904                                 dev_data->domain != domain)
1905                         goto out_unlock;
1906
1907                 /* Do real assignment */
1908                 if (alias_data->domain == NULL)
1909                         do_attach(alias_data, domain);
1910
1911                 atomic_inc(&alias_data->bind);
1912         }
1913
1914         if (dev_data->domain == NULL)
1915                 do_attach(dev_data, domain);
1916
1917         atomic_inc(&dev_data->bind);
1918
1919         ret = 0;
1920
1921 out_unlock:
1922
1923         /* ready */
1924         spin_unlock(&domain->lock);
1925
1926         return ret;
1927 }
1928
1929
1930 static void pdev_iommuv2_disable(struct pci_dev *pdev)
1931 {
1932         pci_disable_ats(pdev);
1933         pci_disable_pri(pdev);
1934         pci_disable_pasid(pdev);
1935 }
1936
1937 static int pdev_iommuv2_enable(struct pci_dev *pdev)
1938 {
1939         int ret;
1940
1941         /* Only allow access to user-accessible pages */
1942         ret = pci_enable_pasid(pdev, 0);
1943         if (ret)
1944                 goto out_err;
1945
1946         /* First reset the PRI state of the device */
1947         ret = pci_reset_pri(pdev);
1948         if (ret)
1949                 goto out_err;
1950
1951         /* FIXME: Hardcode number of outstanding requests for now */
1952         ret = pci_enable_pri(pdev, 32);
1953         if (ret)
1954                 goto out_err;
1955
1956         ret = pci_enable_ats(pdev, PAGE_SHIFT);
1957         if (ret)
1958                 goto out_err;
1959
1960         return 0;
1961
1962 out_err:
1963         pci_disable_pri(pdev);
1964         pci_disable_pasid(pdev);
1965
1966         return ret;
1967 }
1968
1969 /* FIXME: Move this to PCI code */
1970 #define PCI_PRI_TLP_OFF         (1 << 2)
1971
1972 bool pci_pri_tlp_required(struct pci_dev *pdev)
1973 {
1974         u16 control;
1975         int pos;
1976
1977         pos = pci_find_ext_capability(pdev, PCI_PRI_CAP);
1978         if (!pos)
1979                 return false;
1980
1981         pci_read_config_word(pdev, pos + PCI_PRI_CONTROL_OFF, &control);
1982
1983         return (control & PCI_PRI_TLP_OFF) ? true : false;
1984 }
1985
1986 /*
1987  * If a device is not yet associated with a domain, this function does
1988  * assigns it visible for the hardware
1989  */
1990 static int attach_device(struct device *dev,
1991                          struct protection_domain *domain)
1992 {
1993         struct pci_dev *pdev = to_pci_dev(dev);
1994         struct iommu_dev_data *dev_data;
1995         unsigned long flags;
1996         int ret;
1997
1998         dev_data = get_dev_data(dev);
1999
2000         if (domain->flags & PD_IOMMUV2_MASK) {
2001                 if (!dev_data->iommu_v2 || !dev_data->passthrough)
2002                         return -EINVAL;
2003
2004                 if (pdev_iommuv2_enable(pdev) != 0)
2005                         return -EINVAL;
2006
2007                 dev_data->ats.enabled = true;
2008                 dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
2009                 dev_data->pri_tlp     = pci_pri_tlp_required(pdev);
2010         } else if (amd_iommu_iotlb_sup &&
2011                    pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
2012                 dev_data->ats.enabled = true;
2013                 dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
2014         }
2015
2016         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2017         ret = __attach_device(dev_data, domain);
2018         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2019
2020         /*
2021          * We might boot into a crash-kernel here. The crashed kernel
2022          * left the caches in the IOMMU dirty. So we have to flush
2023          * here to evict all dirty stuff.
2024          */
2025         domain_flush_tlb_pde(domain);
2026
2027         return ret;
2028 }
2029
2030 /*
2031  * Removes a device from a protection domain (unlocked)
2032  */
2033 static void __detach_device(struct iommu_dev_data *dev_data)
2034 {
2035         struct protection_domain *domain;
2036         unsigned long flags;
2037
2038         BUG_ON(!dev_data->domain);
2039
2040         domain = dev_data->domain;
2041
2042         spin_lock_irqsave(&domain->lock, flags);
2043
2044         if (dev_data->alias_data != NULL) {
2045                 struct iommu_dev_data *alias_data = dev_data->alias_data;
2046
2047                 if (atomic_dec_and_test(&alias_data->bind))
2048                         do_detach(alias_data);
2049         }
2050
2051         if (atomic_dec_and_test(&dev_data->bind))
2052                 do_detach(dev_data);
2053
2054         spin_unlock_irqrestore(&domain->lock, flags);
2055
2056         /*
2057          * If we run in passthrough mode the device must be assigned to the
2058          * passthrough domain if it is detached from any other domain.
2059          * Make sure we can deassign from the pt_domain itself.
2060          */
2061         if (dev_data->passthrough &&
2062             (dev_data->domain == NULL && domain != pt_domain))
2063                 __attach_device(dev_data, pt_domain);
2064 }
2065
2066 /*
2067  * Removes a device from a protection domain (with devtable_lock held)
2068  */
2069 static void detach_device(struct device *dev)
2070 {
2071         struct protection_domain *domain;
2072         struct iommu_dev_data *dev_data;
2073         unsigned long flags;
2074
2075         dev_data = get_dev_data(dev);
2076         domain   = dev_data->domain;
2077
2078         /* lock device table */
2079         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2080         __detach_device(dev_data);
2081         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2082
2083         if (domain->flags & PD_IOMMUV2_MASK)
2084                 pdev_iommuv2_disable(to_pci_dev(dev));
2085         else if (dev_data->ats.enabled)
2086                 pci_disable_ats(to_pci_dev(dev));
2087
2088         dev_data->ats.enabled = false;
2089 }
2090
2091 /*
2092  * Find out the protection domain structure for a given PCI device. This
2093  * will give us the pointer to the page table root for example.
2094  */
2095 static struct protection_domain *domain_for_device(struct device *dev)
2096 {
2097         struct iommu_dev_data *dev_data;
2098         struct protection_domain *dom = NULL;
2099         unsigned long flags;
2100
2101         dev_data   = get_dev_data(dev);
2102
2103         if (dev_data->domain)
2104                 return dev_data->domain;
2105
2106         if (dev_data->alias_data != NULL) {
2107                 struct iommu_dev_data *alias_data = dev_data->alias_data;
2108
2109                 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
2110                 if (alias_data->domain != NULL) {
2111                         __attach_device(dev_data, alias_data->domain);
2112                         dom = alias_data->domain;
2113                 }
2114                 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2115         }
2116
2117         return dom;
2118 }
2119
2120 static int device_change_notifier(struct notifier_block *nb,
2121                                   unsigned long action, void *data)
2122 {
2123         struct dma_ops_domain *dma_domain;
2124         struct protection_domain *domain;
2125         struct iommu_dev_data *dev_data;
2126         struct device *dev = data;
2127         struct amd_iommu *iommu;
2128         unsigned long flags;
2129         u16 devid;
2130
2131         if (!check_device(dev))
2132                 return 0;
2133
2134         devid    = get_device_id(dev);
2135         iommu    = amd_iommu_rlookup_table[devid];
2136         dev_data = get_dev_data(dev);
2137
2138         switch (action) {
2139         case BUS_NOTIFY_UNBOUND_DRIVER:
2140
2141                 domain = domain_for_device(dev);
2142
2143                 if (!domain)
2144                         goto out;
2145                 if (dev_data->passthrough)
2146                         break;
2147                 detach_device(dev);
2148                 break;
2149         case BUS_NOTIFY_ADD_DEVICE:
2150
2151                 iommu_init_device(dev);
2152
2153                 domain = domain_for_device(dev);
2154
2155                 /* allocate a protection domain if a device is added */
2156                 dma_domain = find_protection_domain(devid);
2157                 if (dma_domain)
2158                         goto out;
2159                 dma_domain = dma_ops_domain_alloc();
2160                 if (!dma_domain)
2161                         goto out;
2162                 dma_domain->target_dev = devid;
2163
2164                 spin_lock_irqsave(&iommu_pd_list_lock, flags);
2165                 list_add_tail(&dma_domain->list, &iommu_pd_list);
2166                 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
2167
2168                 break;
2169         case BUS_NOTIFY_DEL_DEVICE:
2170
2171                 iommu_uninit_device(dev);
2172
2173         default:
2174                 goto out;
2175         }
2176
2177         iommu_completion_wait(iommu);
2178
2179 out:
2180         return 0;
2181 }
2182
2183 static struct notifier_block device_nb = {
2184         .notifier_call = device_change_notifier,
2185 };
2186
2187 void amd_iommu_init_notifier(void)
2188 {
2189         bus_register_notifier(&pci_bus_type, &device_nb);
2190 }
2191
2192 /*****************************************************************************
2193  *
2194  * The next functions belong to the dma_ops mapping/unmapping code.
2195  *
2196  *****************************************************************************/
2197
2198 /*
2199  * In the dma_ops path we only have the struct device. This function
2200  * finds the corresponding IOMMU, the protection domain and the
2201  * requestor id for a given device.
2202  * If the device is not yet associated with a domain this is also done
2203  * in this function.
2204  */
2205 static struct protection_domain *get_domain(struct device *dev)
2206 {
2207         struct protection_domain *domain;
2208         struct dma_ops_domain *dma_dom;
2209         u16 devid = get_device_id(dev);
2210
2211         if (!check_device(dev))
2212                 return ERR_PTR(-EINVAL);
2213
2214         domain = domain_for_device(dev);
2215         if (domain != NULL && !dma_ops_domain(domain))
2216                 return ERR_PTR(-EBUSY);
2217
2218         if (domain != NULL)
2219                 return domain;
2220
2221         /* Device not bount yet - bind it */
2222         dma_dom = find_protection_domain(devid);
2223         if (!dma_dom)
2224                 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
2225         attach_device(dev, &dma_dom->domain);
2226         DUMP_printk("Using protection domain %d for device %s\n",
2227                     dma_dom->domain.id, dev_name(dev));
2228
2229         return &dma_dom->domain;
2230 }
2231
2232 static void update_device_table(struct protection_domain *domain)
2233 {
2234         struct iommu_dev_data *dev_data;
2235
2236         list_for_each_entry(dev_data, &domain->dev_list, list)
2237                 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
2238 }
2239
2240 static void update_domain(struct protection_domain *domain)
2241 {
2242         if (!domain->updated)
2243                 return;
2244
2245         update_device_table(domain);
2246
2247         domain_flush_devices(domain);
2248         domain_flush_tlb_pde(domain);
2249
2250         domain->updated = false;
2251 }
2252
2253 /*
2254  * This function fetches the PTE for a given address in the aperture
2255  */
2256 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
2257                             unsigned long address)
2258 {
2259         struct aperture_range *aperture;
2260         u64 *pte, *pte_page;
2261
2262         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2263         if (!aperture)
2264                 return NULL;
2265
2266         pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2267         if (!pte) {
2268                 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
2269                                 GFP_ATOMIC);
2270                 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
2271         } else
2272                 pte += PM_LEVEL_INDEX(0, address);
2273
2274         update_domain(&dom->domain);
2275
2276         return pte;
2277 }
2278
2279 /*
2280  * This is the generic map function. It maps one 4kb page at paddr to
2281  * the given address in the DMA address space for the domain.
2282  */
2283 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2284                                      unsigned long address,
2285                                      phys_addr_t paddr,
2286                                      int direction)
2287 {
2288         u64 *pte, __pte;
2289
2290         WARN_ON(address > dom->aperture_size);
2291
2292         paddr &= PAGE_MASK;
2293
2294         pte  = dma_ops_get_pte(dom, address);
2295         if (!pte)
2296                 return DMA_ERROR_CODE;
2297
2298         __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2299
2300         if (direction == DMA_TO_DEVICE)
2301                 __pte |= IOMMU_PTE_IR;
2302         else if (direction == DMA_FROM_DEVICE)
2303                 __pte |= IOMMU_PTE_IW;
2304         else if (direction == DMA_BIDIRECTIONAL)
2305                 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2306
2307         WARN_ON(*pte);
2308
2309         *pte = __pte;
2310
2311         return (dma_addr_t)address;
2312 }
2313
2314 /*
2315  * The generic unmapping function for on page in the DMA address space.
2316  */
2317 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2318                                  unsigned long address)
2319 {
2320         struct aperture_range *aperture;
2321         u64 *pte;
2322
2323         if (address >= dom->aperture_size)
2324                 return;
2325
2326         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2327         if (!aperture)
2328                 return;
2329
2330         pte  = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2331         if (!pte)
2332                 return;
2333
2334         pte += PM_LEVEL_INDEX(0, address);
2335
2336         WARN_ON(!*pte);
2337
2338         *pte = 0ULL;
2339 }
2340
2341 /*
2342  * This function contains common code for mapping of a physically
2343  * contiguous memory region into DMA address space. It is used by all
2344  * mapping functions provided with this IOMMU driver.
2345  * Must be called with the domain lock held.
2346  */
2347 static dma_addr_t __map_single(struct device *dev,
2348                                struct dma_ops_domain *dma_dom,
2349                                phys_addr_t paddr,
2350                                size_t size,
2351                                int dir,
2352                                bool align,
2353                                u64 dma_mask)
2354 {
2355         dma_addr_t offset = paddr & ~PAGE_MASK;
2356         dma_addr_t address, start, ret;
2357         unsigned int pages;
2358         unsigned long align_mask = 0;
2359         int i;
2360
2361         pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2362         paddr &= PAGE_MASK;
2363
2364         INC_STATS_COUNTER(total_map_requests);
2365
2366         if (pages > 1)
2367                 INC_STATS_COUNTER(cross_page);
2368
2369         if (align)
2370                 align_mask = (1UL << get_order(size)) - 1;
2371
2372 retry:
2373         address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2374                                           dma_mask);
2375         if (unlikely(address == DMA_ERROR_CODE)) {
2376                 /*
2377                  * setting next_address here will let the address
2378                  * allocator only scan the new allocated range in the
2379                  * first run. This is a small optimization.
2380                  */
2381                 dma_dom->next_address = dma_dom->aperture_size;
2382
2383                 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2384                         goto out;
2385
2386                 /*
2387                  * aperture was successfully enlarged by 128 MB, try
2388                  * allocation again
2389                  */
2390                 goto retry;
2391         }
2392
2393         start = address;
2394         for (i = 0; i < pages; ++i) {
2395                 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2396                 if (ret == DMA_ERROR_CODE)
2397                         goto out_unmap;
2398
2399                 paddr += PAGE_SIZE;
2400                 start += PAGE_SIZE;
2401         }
2402         address += offset;
2403
2404         ADD_STATS_COUNTER(alloced_io_mem, size);
2405
2406         if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2407                 domain_flush_tlb(&dma_dom->domain);
2408                 dma_dom->need_flush = false;
2409         } else if (unlikely(amd_iommu_np_cache))
2410                 domain_flush_pages(&dma_dom->domain, address, size);
2411
2412 out:
2413         return address;
2414
2415 out_unmap:
2416
2417         for (--i; i >= 0; --i) {
2418                 start -= PAGE_SIZE;
2419                 dma_ops_domain_unmap(dma_dom, start);
2420         }
2421
2422         dma_ops_free_addresses(dma_dom, address, pages);
2423
2424         return DMA_ERROR_CODE;
2425 }
2426
2427 /*
2428  * Does the reverse of the __map_single function. Must be called with
2429  * the domain lock held too
2430  */
2431 static void __unmap_single(struct dma_ops_domain *dma_dom,
2432                            dma_addr_t dma_addr,
2433                            size_t size,
2434                            int dir)
2435 {
2436         dma_addr_t flush_addr;
2437         dma_addr_t i, start;
2438         unsigned int pages;
2439
2440         if ((dma_addr == DMA_ERROR_CODE) ||
2441             (dma_addr + size > dma_dom->aperture_size))
2442                 return;
2443
2444         flush_addr = dma_addr;
2445         pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2446         dma_addr &= PAGE_MASK;
2447         start = dma_addr;
2448
2449         for (i = 0; i < pages; ++i) {
2450                 dma_ops_domain_unmap(dma_dom, start);
2451                 start += PAGE_SIZE;
2452         }
2453
2454         SUB_STATS_COUNTER(alloced_io_mem, size);
2455
2456         dma_ops_free_addresses(dma_dom, dma_addr, pages);
2457
2458         if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2459                 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2460                 dma_dom->need_flush = false;
2461         }
2462 }
2463
2464 /*
2465  * The exported map_single function for dma_ops.
2466  */
2467 static dma_addr_t map_page(struct device *dev, struct page *page,
2468                            unsigned long offset, size_t size,
2469                            enum dma_data_direction dir,
2470                            struct dma_attrs *attrs)
2471 {
2472         unsigned long flags;
2473         struct protection_domain *domain;
2474         dma_addr_t addr;
2475         u64 dma_mask;
2476         phys_addr_t paddr = page_to_phys(page) + offset;
2477
2478         INC_STATS_COUNTER(cnt_map_single);
2479
2480         domain = get_domain(dev);
2481         if (PTR_ERR(domain) == -EINVAL)
2482                 return (dma_addr_t)paddr;
2483         else if (IS_ERR(domain))
2484                 return DMA_ERROR_CODE;
2485
2486         dma_mask = *dev->dma_mask;
2487
2488         spin_lock_irqsave(&domain->lock, flags);
2489
2490         addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2491                             dma_mask);
2492         if (addr == DMA_ERROR_CODE)
2493                 goto out;
2494
2495         domain_flush_complete(domain);
2496
2497 out:
2498         spin_unlock_irqrestore(&domain->lock, flags);
2499
2500         return addr;
2501 }
2502
2503 /*
2504  * The exported unmap_single function for dma_ops.
2505  */
2506 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2507                        enum dma_data_direction dir, struct dma_attrs *attrs)
2508 {
2509         unsigned long flags;
2510         struct protection_domain *domain;
2511
2512         INC_STATS_COUNTER(cnt_unmap_single);
2513
2514         domain = get_domain(dev);
2515         if (IS_ERR(domain))
2516                 return;
2517
2518         spin_lock_irqsave(&domain->lock, flags);
2519
2520         __unmap_single(domain->priv, dma_addr, size, dir);
2521
2522         domain_flush_complete(domain);
2523
2524         spin_unlock_irqrestore(&domain->lock, flags);
2525 }
2526
2527 /*
2528  * This is a special map_sg function which is used if we should map a
2529  * device which is not handled by an AMD IOMMU in the system.
2530  */
2531 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2532                            int nelems, int dir)
2533 {
2534         struct scatterlist *s;
2535         int i;
2536
2537         for_each_sg(sglist, s, nelems, i) {
2538                 s->dma_address = (dma_addr_t)sg_phys(s);
2539                 s->dma_length  = s->length;
2540         }
2541
2542         return nelems;
2543 }
2544
2545 /*
2546  * The exported map_sg function for dma_ops (handles scatter-gather
2547  * lists).
2548  */
2549 static int map_sg(struct device *dev, struct scatterlist *sglist,
2550                   int nelems, enum dma_data_direction dir,
2551                   struct dma_attrs *attrs)
2552 {
2553         unsigned long flags;
2554         struct protection_domain *domain;
2555         int i;
2556         struct scatterlist *s;
2557         phys_addr_t paddr;
2558         int mapped_elems = 0;
2559         u64 dma_mask;
2560
2561         INC_STATS_COUNTER(cnt_map_sg);
2562
2563         domain = get_domain(dev);
2564         if (PTR_ERR(domain) == -EINVAL)
2565                 return map_sg_no_iommu(dev, sglist, nelems, dir);
2566         else if (IS_ERR(domain))
2567                 return 0;
2568
2569         dma_mask = *dev->dma_mask;
2570
2571         spin_lock_irqsave(&domain->lock, flags);
2572
2573         for_each_sg(sglist, s, nelems, i) {
2574                 paddr = sg_phys(s);
2575
2576                 s->dma_address = __map_single(dev, domain->priv,
2577                                               paddr, s->length, dir, false,
2578                                               dma_mask);
2579
2580                 if (s->dma_address) {
2581                         s->dma_length = s->length;
2582                         mapped_elems++;
2583                 } else
2584                         goto unmap;
2585         }
2586
2587         domain_flush_complete(domain);
2588
2589 out:
2590         spin_unlock_irqrestore(&domain->lock, flags);
2591
2592         return mapped_elems;
2593 unmap:
2594         for_each_sg(sglist, s, mapped_elems, i) {
2595                 if (s->dma_address)
2596                         __unmap_single(domain->priv, s->dma_address,
2597                                        s->dma_length, dir);
2598                 s->dma_address = s->dma_length = 0;
2599         }
2600
2601         mapped_elems = 0;
2602
2603         goto out;
2604 }
2605
2606 /*
2607  * The exported map_sg function for dma_ops (handles scatter-gather
2608  * lists).
2609  */
2610 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2611                      int nelems, enum dma_data_direction dir,
2612                      struct dma_attrs *attrs)
2613 {
2614         unsigned long flags;
2615         struct protection_domain *domain;
2616         struct scatterlist *s;
2617         int i;
2618
2619         INC_STATS_COUNTER(cnt_unmap_sg);
2620
2621         domain = get_domain(dev);
2622         if (IS_ERR(domain))
2623                 return;
2624
2625         spin_lock_irqsave(&domain->lock, flags);
2626
2627         for_each_sg(sglist, s, nelems, i) {
2628                 __unmap_single(domain->priv, s->dma_address,
2629                                s->dma_length, dir);
2630                 s->dma_address = s->dma_length = 0;
2631         }
2632
2633         domain_flush_complete(domain);
2634
2635         spin_unlock_irqrestore(&domain->lock, flags);
2636 }
2637
2638 /*
2639  * The exported alloc_coherent function for dma_ops.
2640  */
2641 static void *alloc_coherent(struct device *dev, size_t size,
2642                             dma_addr_t *dma_addr, gfp_t flag)
2643 {
2644         unsigned long flags;
2645         void *virt_addr;
2646         struct protection_domain *domain;
2647         phys_addr_t paddr;
2648         u64 dma_mask = dev->coherent_dma_mask;
2649
2650         INC_STATS_COUNTER(cnt_alloc_coherent);
2651
2652         domain = get_domain(dev);
2653         if (PTR_ERR(domain) == -EINVAL) {
2654                 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2655                 *dma_addr = __pa(virt_addr);
2656                 return virt_addr;
2657         } else if (IS_ERR(domain))
2658                 return NULL;
2659
2660         dma_mask  = dev->coherent_dma_mask;
2661         flag     &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2662         flag     |= __GFP_ZERO;
2663
2664         virt_addr = (void *)__get_free_pages(flag, get_order(size));
2665         if (!virt_addr)
2666                 return NULL;
2667
2668         paddr = virt_to_phys(virt_addr);
2669
2670         if (!dma_mask)
2671                 dma_mask = *dev->dma_mask;
2672
2673         spin_lock_irqsave(&domain->lock, flags);
2674
2675         *dma_addr = __map_single(dev, domain->priv, paddr,
2676                                  size, DMA_BIDIRECTIONAL, true, dma_mask);
2677
2678         if (*dma_addr == DMA_ERROR_CODE) {
2679                 spin_unlock_irqrestore(&domain->lock, flags);
2680                 goto out_free;
2681         }
2682
2683         domain_flush_complete(domain);
2684
2685         spin_unlock_irqrestore(&domain->lock, flags);
2686
2687         return virt_addr;
2688
2689 out_free:
2690
2691         free_pages((unsigned long)virt_addr, get_order(size));
2692
2693         return NULL;
2694 }
2695
2696 /*
2697  * The exported free_coherent function for dma_ops.
2698  */
2699 static void free_coherent(struct device *dev, size_t size,
2700                           void *virt_addr, dma_addr_t dma_addr)
2701 {
2702         unsigned long flags;
2703         struct protection_domain *domain;
2704
2705         INC_STATS_COUNTER(cnt_free_coherent);
2706
2707         domain = get_domain(dev);
2708         if (IS_ERR(domain))
2709                 goto free_mem;
2710
2711         spin_lock_irqsave(&domain->lock, flags);
2712
2713         __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2714
2715         domain_flush_complete(domain);
2716
2717         spin_unlock_irqrestore(&domain->lock, flags);
2718
2719 free_mem:
2720         free_pages((unsigned long)virt_addr, get_order(size));
2721 }
2722
2723 /*
2724  * This function is called by the DMA layer to find out if we can handle a
2725  * particular device. It is part of the dma_ops.
2726  */
2727 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2728 {
2729         return check_device(dev);
2730 }
2731
2732 /*
2733  * The function for pre-allocating protection domains.
2734  *
2735  * If the driver core informs the DMA layer if a driver grabs a device
2736  * we don't need to preallocate the protection domains anymore.
2737  * For now we have to.
2738  */
2739 static void prealloc_protection_domains(void)
2740 {
2741         struct iommu_dev_data *dev_data;
2742         struct dma_ops_domain *dma_dom;
2743         struct pci_dev *dev = NULL;
2744         u16 devid;
2745
2746         for_each_pci_dev(dev) {
2747
2748                 /* Do we handle this device? */
2749                 if (!check_device(&dev->dev))
2750                         continue;
2751
2752                 dev_data = get_dev_data(&dev->dev);
2753                 if (!amd_iommu_force_isolation && dev_data->iommu_v2) {
2754                         /* Make sure passthrough domain is allocated */
2755                         alloc_passthrough_domain();
2756                         dev_data->passthrough = true;
2757                         attach_device(&dev->dev, pt_domain);
2758                         pr_info("AMD-Vi: Using passthough domain for device %s\n",
2759                                 dev_name(&dev->dev));
2760                 }
2761
2762                 /* Is there already any domain for it? */
2763                 if (domain_for_device(&dev->dev))
2764                         continue;
2765
2766                 devid = get_device_id(&dev->dev);
2767
2768                 dma_dom = dma_ops_domain_alloc();
2769                 if (!dma_dom)
2770                         continue;
2771                 init_unity_mappings_for_device(dma_dom, devid);
2772                 dma_dom->target_dev = devid;
2773
2774                 attach_device(&dev->dev, &dma_dom->domain);
2775
2776                 list_add_tail(&dma_dom->list, &iommu_pd_list);
2777         }
2778 }
2779
2780 static struct dma_map_ops amd_iommu_dma_ops = {
2781         .alloc_coherent = alloc_coherent,
2782         .free_coherent = free_coherent,
2783         .map_page = map_page,
2784         .unmap_page = unmap_page,
2785         .map_sg = map_sg,
2786         .unmap_sg = unmap_sg,
2787         .dma_supported = amd_iommu_dma_supported,
2788 };
2789
2790 static unsigned device_dma_ops_init(void)
2791 {
2792         struct iommu_dev_data *dev_data;
2793         struct pci_dev *pdev = NULL;
2794         unsigned unhandled = 0;
2795
2796         for_each_pci_dev(pdev) {
2797                 if (!check_device(&pdev->dev)) {
2798                         unhandled += 1;
2799                         continue;
2800                 }
2801
2802                 dev_data = get_dev_data(&pdev->dev);
2803
2804                 if (!dev_data->passthrough)
2805                         pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
2806                 else
2807                         pdev->dev.archdata.dma_ops = &nommu_dma_ops;
2808         }
2809
2810         return unhandled;
2811 }
2812
2813 /*
2814  * The function which clues the AMD IOMMU driver into dma_ops.
2815  */
2816
2817 void __init amd_iommu_init_api(void)
2818 {
2819         bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2820 }
2821
2822 int __init amd_iommu_init_dma_ops(void)
2823 {
2824         struct amd_iommu *iommu;
2825         int ret, unhandled;
2826
2827         /*
2828          * first allocate a default protection domain for every IOMMU we
2829          * found in the system. Devices not assigned to any other
2830          * protection domain will be assigned to the default one.
2831          */
2832         for_each_iommu(iommu) {
2833                 iommu->default_dom = dma_ops_domain_alloc();
2834                 if (iommu->default_dom == NULL)
2835                         return -ENOMEM;
2836                 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
2837                 ret = iommu_init_unity_mappings(iommu);
2838                 if (ret)
2839                         goto free_domains;
2840         }
2841
2842         /*
2843          * Pre-allocate the protection domains for each device.
2844          */
2845         prealloc_protection_domains();
2846
2847         iommu_detected = 1;
2848         swiotlb = 0;
2849
2850         /* Make the driver finally visible to the drivers */
2851         unhandled = device_dma_ops_init();
2852         if (unhandled && max_pfn > MAX_DMA32_PFN) {
2853                 /* There are unhandled devices - initialize swiotlb for them */
2854                 swiotlb = 1;
2855         }
2856
2857         amd_iommu_stats_init();
2858
2859         return 0;
2860
2861 free_domains:
2862
2863         for_each_iommu(iommu) {
2864                 if (iommu->default_dom)
2865                         dma_ops_domain_free(iommu->default_dom);
2866         }
2867
2868         return ret;
2869 }
2870
2871 /*****************************************************************************
2872  *
2873  * The following functions belong to the exported interface of AMD IOMMU
2874  *
2875  * This interface allows access to lower level functions of the IOMMU
2876  * like protection domain handling and assignement of devices to domains
2877  * which is not possible with the dma_ops interface.
2878  *
2879  *****************************************************************************/
2880
2881 static void cleanup_domain(struct protection_domain *domain)
2882 {
2883         struct iommu_dev_data *dev_data, *next;
2884         unsigned long flags;
2885
2886         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2887
2888         list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
2889                 __detach_device(dev_data);
2890                 atomic_set(&dev_data->bind, 0);
2891         }
2892
2893         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2894 }
2895
2896 static void protection_domain_free(struct protection_domain *domain)
2897 {
2898         if (!domain)
2899                 return;
2900
2901         del_domain_from_list(domain);
2902
2903         if (domain->id)
2904                 domain_id_free(domain->id);
2905
2906         kfree(domain);
2907 }
2908
2909 static struct protection_domain *protection_domain_alloc(void)
2910 {
2911         struct protection_domain *domain;
2912
2913         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2914         if (!domain)
2915                 return NULL;
2916
2917         spin_lock_init(&domain->lock);
2918         mutex_init(&domain->api_lock);
2919         domain->id = domain_id_alloc();
2920         if (!domain->id)
2921                 goto out_err;
2922         INIT_LIST_HEAD(&domain->dev_list);
2923
2924         add_domain_to_list(domain);
2925
2926         return domain;
2927
2928 out_err:
2929         kfree(domain);
2930
2931         return NULL;
2932 }
2933
2934 static int __init alloc_passthrough_domain(void)
2935 {
2936         if (pt_domain != NULL)
2937                 return 0;
2938
2939         /* allocate passthrough domain */
2940         pt_domain = protection_domain_alloc();
2941         if (!pt_domain)
2942                 return -ENOMEM;
2943
2944         pt_domain->mode = PAGE_MODE_NONE;
2945
2946         return 0;
2947 }
2948 static int amd_iommu_domain_init(struct iommu_domain *dom)
2949 {
2950         struct protection_domain *domain;
2951
2952         domain = protection_domain_alloc();
2953         if (!domain)
2954                 goto out_free;
2955
2956         domain->mode    = PAGE_MODE_3_LEVEL;
2957         domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2958         if (!domain->pt_root)
2959                 goto out_free;
2960
2961         domain->iommu_domain = dom;
2962
2963         dom->priv = domain;
2964
2965         return 0;
2966
2967 out_free:
2968         protection_domain_free(domain);
2969
2970         return -ENOMEM;
2971 }
2972
2973 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
2974 {
2975         struct protection_domain *domain = dom->priv;
2976
2977         if (!domain)
2978                 return;
2979
2980         if (domain->dev_cnt > 0)
2981                 cleanup_domain(domain);
2982
2983         BUG_ON(domain->dev_cnt != 0);
2984
2985         if (domain->mode != PAGE_MODE_NONE)
2986                 free_pagetable(domain);
2987
2988         if (domain->flags & PD_IOMMUV2_MASK)
2989                 free_gcr3_table(domain);
2990
2991         protection_domain_free(domain);
2992
2993         dom->priv = NULL;
2994 }
2995
2996 static void amd_iommu_detach_device(struct iommu_domain *dom,
2997                                     struct device *dev)
2998 {
2999         struct iommu_dev_data *dev_data = dev->archdata.iommu;
3000         struct amd_iommu *iommu;
3001         u16 devid;
3002
3003         if (!check_device(dev))
3004                 return;
3005
3006         devid = get_device_id(dev);
3007
3008         if (dev_data->domain != NULL)
3009                 detach_device(dev);
3010
3011         iommu = amd_iommu_rlookup_table[devid];
3012         if (!iommu)
3013                 return;
3014
3015         iommu_completion_wait(iommu);
3016 }
3017
3018 static int amd_iommu_attach_device(struct iommu_domain *dom,
3019                                    struct device *dev)
3020 {
3021         struct protection_domain *domain = dom->priv;
3022         struct iommu_dev_data *dev_data;
3023         struct amd_iommu *iommu;
3024         int ret;
3025
3026         if (!check_device(dev))
3027                 return -EINVAL;
3028
3029         dev_data = dev->archdata.iommu;
3030
3031         iommu = amd_iommu_rlookup_table[dev_data->devid];
3032         if (!iommu)
3033                 return -EINVAL;
3034
3035         if (dev_data->domain)
3036                 detach_device(dev);
3037
3038         ret = attach_device(dev, domain);
3039
3040         iommu_completion_wait(iommu);
3041
3042         return ret;
3043 }
3044
3045 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
3046                          phys_addr_t paddr, int gfp_order, int iommu_prot)
3047 {
3048         unsigned long page_size = 0x1000UL << gfp_order;
3049         struct protection_domain *domain = dom->priv;
3050         int prot = 0;
3051         int ret;
3052
3053         if (domain->mode == PAGE_MODE_NONE)
3054                 return -EINVAL;
3055
3056         if (iommu_prot & IOMMU_READ)
3057                 prot |= IOMMU_PROT_IR;
3058         if (iommu_prot & IOMMU_WRITE)
3059                 prot |= IOMMU_PROT_IW;
3060
3061         mutex_lock(&domain->api_lock);
3062         ret = iommu_map_page(domain, iova, paddr, prot, page_size);
3063         mutex_unlock(&domain->api_lock);
3064
3065         return ret;
3066 }
3067
3068 static int amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
3069                            int gfp_order)
3070 {
3071         struct protection_domain *domain = dom->priv;
3072         unsigned long page_size, unmap_size;
3073
3074         if (domain->mode == PAGE_MODE_NONE)
3075                 return -EINVAL;
3076
3077         page_size  = 0x1000UL << gfp_order;
3078
3079         mutex_lock(&domain->api_lock);
3080         unmap_size = iommu_unmap_page(domain, iova, page_size);
3081         mutex_unlock(&domain->api_lock);
3082
3083         domain_flush_tlb_pde(domain);
3084
3085         return get_order(unmap_size);
3086 }
3087
3088 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
3089                                           unsigned long iova)
3090 {
3091         struct protection_domain *domain = dom->priv;
3092         unsigned long offset_mask;
3093         phys_addr_t paddr;
3094         u64 *pte, __pte;
3095
3096         if (domain->mode == PAGE_MODE_NONE)
3097                 return iova;
3098
3099         pte = fetch_pte(domain, iova);
3100
3101         if (!pte || !IOMMU_PTE_PRESENT(*pte))
3102                 return 0;
3103
3104         if (PM_PTE_LEVEL(*pte) == 0)
3105                 offset_mask = PAGE_SIZE - 1;
3106         else
3107                 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
3108
3109         __pte = *pte & PM_ADDR_MASK;
3110         paddr = (__pte & ~offset_mask) | (iova & offset_mask);
3111
3112         return paddr;
3113 }
3114
3115 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
3116                                     unsigned long cap)
3117 {
3118         switch (cap) {
3119         case IOMMU_CAP_CACHE_COHERENCY:
3120                 return 1;
3121         }
3122
3123         return 0;
3124 }
3125
3126 static struct iommu_ops amd_iommu_ops = {
3127         .domain_init = amd_iommu_domain_init,
3128         .domain_destroy = amd_iommu_domain_destroy,
3129         .attach_dev = amd_iommu_attach_device,
3130         .detach_dev = amd_iommu_detach_device,
3131         .map = amd_iommu_map,
3132         .unmap = amd_iommu_unmap,
3133         .iova_to_phys = amd_iommu_iova_to_phys,
3134         .domain_has_cap = amd_iommu_domain_has_cap,
3135 };
3136
3137 /*****************************************************************************
3138  *
3139  * The next functions do a basic initialization of IOMMU for pass through
3140  * mode
3141  *
3142  * In passthrough mode the IOMMU is initialized and enabled but not used for
3143  * DMA-API translation.
3144  *
3145  *****************************************************************************/
3146
3147 int __init amd_iommu_init_passthrough(void)
3148 {
3149         struct iommu_dev_data *dev_data;
3150         struct pci_dev *dev = NULL;
3151         struct amd_iommu *iommu;
3152         u16 devid;
3153         int ret;
3154
3155         ret = alloc_passthrough_domain();
3156         if (ret)
3157                 return ret;
3158
3159         for_each_pci_dev(dev) {
3160                 if (!check_device(&dev->dev))
3161                         continue;
3162
3163                 dev_data = get_dev_data(&dev->dev);
3164                 dev_data->passthrough = true;
3165
3166                 devid = get_device_id(&dev->dev);
3167
3168                 iommu = amd_iommu_rlookup_table[devid];
3169                 if (!iommu)
3170                         continue;
3171
3172                 attach_device(&dev->dev, pt_domain);
3173         }
3174
3175         pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
3176
3177         return 0;
3178 }
3179
3180 /* IOMMUv2 specific functions */
3181 int amd_iommu_register_ppr_notifier(struct notifier_block *nb)
3182 {
3183         return atomic_notifier_chain_register(&ppr_notifier, nb);
3184 }
3185 EXPORT_SYMBOL(amd_iommu_register_ppr_notifier);
3186
3187 int amd_iommu_unregister_ppr_notifier(struct notifier_block *nb)
3188 {
3189         return atomic_notifier_chain_unregister(&ppr_notifier, nb);
3190 }
3191 EXPORT_SYMBOL(amd_iommu_unregister_ppr_notifier);
3192
3193 void amd_iommu_domain_direct_map(struct iommu_domain *dom)
3194 {
3195         struct protection_domain *domain = dom->priv;
3196         unsigned long flags;
3197
3198         spin_lock_irqsave(&domain->lock, flags);
3199
3200         /* Update data structure */
3201         domain->mode    = PAGE_MODE_NONE;
3202         domain->updated = true;
3203
3204         /* Make changes visible to IOMMUs */
3205         update_domain(domain);
3206
3207         /* Page-table is not visible to IOMMU anymore, so free it */
3208         free_pagetable(domain);
3209
3210         spin_unlock_irqrestore(&domain->lock, flags);
3211 }
3212 EXPORT_SYMBOL(amd_iommu_domain_direct_map);
3213
3214 int amd_iommu_domain_enable_v2(struct iommu_domain *dom, int pasids)
3215 {
3216         struct protection_domain *domain = dom->priv;
3217         unsigned long flags;
3218         int levels, ret;
3219
3220         if (pasids <= 0 || pasids > (PASID_MASK + 1))
3221                 return -EINVAL;
3222
3223         /* Number of GCR3 table levels required */
3224         for (levels = 0; (pasids - 1) & ~0x1ff; pasids >>= 9)
3225                 levels += 1;
3226
3227         if (levels > amd_iommu_max_glx_val)
3228                 return -EINVAL;
3229
3230         spin_lock_irqsave(&domain->lock, flags);
3231
3232         /*
3233          * Save us all sanity checks whether devices already in the
3234          * domain support IOMMUv2. Just force that the domain has no
3235          * devices attached when it is switched into IOMMUv2 mode.
3236          */
3237         ret = -EBUSY;
3238         if (domain->dev_cnt > 0 || domain->flags & PD_IOMMUV2_MASK)
3239                 goto out;
3240
3241         ret = -ENOMEM;
3242         domain->gcr3_tbl = (void *)get_zeroed_page(GFP_ATOMIC);
3243         if (domain->gcr3_tbl == NULL)
3244                 goto out;
3245
3246         domain->glx      = levels;
3247         domain->flags   |= PD_IOMMUV2_MASK;
3248         domain->updated  = true;
3249
3250         update_domain(domain);
3251
3252         ret = 0;
3253
3254 out:
3255         spin_unlock_irqrestore(&domain->lock, flags);
3256
3257         return ret;
3258 }
3259 EXPORT_SYMBOL(amd_iommu_domain_enable_v2);
3260
3261 static int __flush_pasid(struct protection_domain *domain, int pasid,
3262                          u64 address, bool size)
3263 {
3264         struct iommu_dev_data *dev_data;
3265         struct iommu_cmd cmd;
3266         int i, ret;
3267
3268         if (!(domain->flags & PD_IOMMUV2_MASK))
3269                 return -EINVAL;
3270
3271         build_inv_iommu_pasid(&cmd, domain->id, pasid, address, size);
3272
3273         /*
3274          * IOMMU TLB needs to be flushed before Device TLB to
3275          * prevent device TLB refill from IOMMU TLB
3276          */
3277         for (i = 0; i < amd_iommus_present; ++i) {
3278                 if (domain->dev_iommu[i] == 0)
3279                         continue;
3280
3281                 ret = iommu_queue_command(amd_iommus[i], &cmd);
3282                 if (ret != 0)
3283                         goto out;
3284         }
3285
3286         /* Wait until IOMMU TLB flushes are complete */
3287         domain_flush_complete(domain);
3288
3289         /* Now flush device TLBs */
3290         list_for_each_entry(dev_data, &domain->dev_list, list) {
3291                 struct amd_iommu *iommu;
3292                 int qdep;
3293
3294                 BUG_ON(!dev_data->ats.enabled);
3295
3296                 qdep  = dev_data->ats.qdep;
3297                 iommu = amd_iommu_rlookup_table[dev_data->devid];
3298
3299                 build_inv_iotlb_pasid(&cmd, dev_data->devid, pasid,
3300                                       qdep, address, size);
3301
3302                 ret = iommu_queue_command(iommu, &cmd);
3303                 if (ret != 0)
3304                         goto out;
3305         }
3306
3307         /* Wait until all device TLBs are flushed */
3308         domain_flush_complete(domain);
3309
3310         ret = 0;
3311
3312 out:
3313
3314         return ret;
3315 }
3316
3317 static int __amd_iommu_flush_page(struct protection_domain *domain, int pasid,
3318                                   u64 address)
3319 {
3320         return __flush_pasid(domain, pasid, address, false);
3321 }
3322
3323 int amd_iommu_flush_page(struct iommu_domain *dom, int pasid,
3324                          u64 address)
3325 {
3326         struct protection_domain *domain = dom->priv;
3327         unsigned long flags;
3328         int ret;
3329
3330         spin_lock_irqsave(&domain->lock, flags);
3331         ret = __amd_iommu_flush_page(domain, pasid, address);
3332         spin_unlock_irqrestore(&domain->lock, flags);
3333
3334         return ret;
3335 }
3336 EXPORT_SYMBOL(amd_iommu_flush_page);
3337
3338 static int __amd_iommu_flush_tlb(struct protection_domain *domain, int pasid)
3339 {
3340         return __flush_pasid(domain, pasid, CMD_INV_IOMMU_ALL_PAGES_ADDRESS,
3341                              true);
3342 }
3343
3344 int amd_iommu_flush_tlb(struct iommu_domain *dom, int pasid)
3345 {
3346         struct protection_domain *domain = dom->priv;
3347         unsigned long flags;
3348         int ret;
3349
3350         spin_lock_irqsave(&domain->lock, flags);
3351         ret = __amd_iommu_flush_tlb(domain, pasid);
3352         spin_unlock_irqrestore(&domain->lock, flags);
3353
3354         return ret;
3355 }
3356 EXPORT_SYMBOL(amd_iommu_flush_tlb);
3357
3358 static u64 *__get_gcr3_pte(u64 *root, int level, int pasid, bool alloc)
3359 {
3360         int index;
3361         u64 *pte;
3362
3363         while (true) {
3364
3365                 index = (pasid >> (9 * level)) & 0x1ff;
3366                 pte   = &root[index];
3367
3368                 if (level == 0)
3369                         break;
3370
3371                 if (!(*pte & GCR3_VALID)) {
3372                         if (!alloc)
3373                                 return NULL;
3374
3375                         root = (void *)get_zeroed_page(GFP_ATOMIC);
3376                         if (root == NULL)
3377                                 return NULL;
3378
3379                         *pte = __pa(root) | GCR3_VALID;
3380                 }
3381
3382                 root = __va(*pte & PAGE_MASK);
3383
3384                 level -= 1;
3385         }
3386
3387         return pte;
3388 }
3389
3390 static int __set_gcr3(struct protection_domain *domain, int pasid,
3391                       unsigned long cr3)
3392 {
3393         u64 *pte;
3394
3395         if (domain->mode != PAGE_MODE_NONE)
3396                 return -EINVAL;
3397
3398         pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, true);
3399         if (pte == NULL)
3400                 return -ENOMEM;
3401
3402         *pte = (cr3 & PAGE_MASK) | GCR3_VALID;
3403
3404         return __amd_iommu_flush_tlb(domain, pasid);
3405 }
3406
3407 static int __clear_gcr3(struct protection_domain *domain, int pasid)
3408 {
3409         u64 *pte;
3410
3411         if (domain->mode != PAGE_MODE_NONE)
3412                 return -EINVAL;
3413
3414         pte = __get_gcr3_pte(domain->gcr3_tbl, domain->glx, pasid, false);
3415         if (pte == NULL)
3416                 return 0;
3417
3418         *pte = 0;
3419
3420         return __amd_iommu_flush_tlb(domain, pasid);
3421 }
3422
3423 int amd_iommu_domain_set_gcr3(struct iommu_domain *dom, int pasid,
3424                               unsigned long cr3)
3425 {
3426         struct protection_domain *domain = dom->priv;
3427         unsigned long flags;
3428         int ret;
3429
3430         spin_lock_irqsave(&domain->lock, flags);
3431         ret = __set_gcr3(domain, pasid, cr3);
3432         spin_unlock_irqrestore(&domain->lock, flags);
3433
3434         return ret;
3435 }
3436 EXPORT_SYMBOL(amd_iommu_domain_set_gcr3);
3437
3438 int amd_iommu_domain_clear_gcr3(struct iommu_domain *dom, int pasid)
3439 {
3440         struct protection_domain *domain = dom->priv;
3441         unsigned long flags;
3442         int ret;
3443
3444         spin_lock_irqsave(&domain->lock, flags);
3445         ret = __clear_gcr3(domain, pasid);
3446         spin_unlock_irqrestore(&domain->lock, flags);
3447
3448         return ret;
3449 }
3450 EXPORT_SYMBOL(amd_iommu_domain_clear_gcr3);
3451
3452 int amd_iommu_complete_ppr(struct pci_dev *pdev, int pasid,
3453                            int status, int tag)
3454 {
3455         struct iommu_dev_data *dev_data;
3456         struct amd_iommu *iommu;
3457         struct iommu_cmd cmd;
3458
3459         dev_data = get_dev_data(&pdev->dev);
3460         iommu    = amd_iommu_rlookup_table[dev_data->devid];
3461
3462         build_complete_ppr(&cmd, dev_data->devid, pasid, status,
3463                            tag, dev_data->pri_tlp);
3464
3465         return iommu_queue_command(iommu, &cmd);
3466 }
3467 EXPORT_SYMBOL(amd_iommu_complete_ppr);
3468
3469 struct iommu_domain *amd_iommu_get_v2_domain(struct pci_dev *pdev)
3470 {
3471         struct protection_domain *domain;
3472
3473         domain = get_domain(&pdev->dev);
3474         if (IS_ERR(domain))
3475                 return NULL;
3476
3477         /* Only return IOMMUv2 domains */
3478         if (!(domain->flags & PD_IOMMUV2_MASK))
3479                 return NULL;
3480
3481         return domain->iommu_domain;
3482 }
3483 EXPORT_SYMBOL(amd_iommu_get_v2_domain);