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