486982f8449f266b7dc3c5334a33a024dc841b94
[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         kfree(dom);
1545 }
1546
1547 /*
1548  * Allocates a new protection domain usable for the dma_ops functions.
1549  * It also initializes the page table and the address allocator data
1550  * structures required for the dma_ops interface
1551  */
1552 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1553 {
1554         struct dma_ops_domain *dma_dom;
1555
1556         dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1557         if (!dma_dom)
1558                 return NULL;
1559
1560         spin_lock_init(&dma_dom->domain.lock);
1561
1562         dma_dom->domain.id = domain_id_alloc();
1563         if (dma_dom->domain.id == 0)
1564                 goto free_dma_dom;
1565         INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1566         dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1567         dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1568         dma_dom->domain.flags = PD_DMA_OPS_MASK;
1569         dma_dom->domain.priv = dma_dom;
1570         if (!dma_dom->domain.pt_root)
1571                 goto free_dma_dom;
1572
1573         dma_dom->need_flush = false;
1574         dma_dom->target_dev = 0xffff;
1575
1576         add_domain_to_list(&dma_dom->domain);
1577
1578         if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1579                 goto free_dma_dom;
1580
1581         /*
1582          * mark the first page as allocated so we never return 0 as
1583          * a valid dma-address. So we can use 0 as error value
1584          */
1585         dma_dom->aperture[0]->bitmap[0] = 1;
1586         dma_dom->next_address = 0;
1587
1588
1589         return dma_dom;
1590
1591 free_dma_dom:
1592         dma_ops_domain_free(dma_dom);
1593
1594         return NULL;
1595 }
1596
1597 /*
1598  * little helper function to check whether a given protection domain is a
1599  * dma_ops domain
1600  */
1601 static bool dma_ops_domain(struct protection_domain *domain)
1602 {
1603         return domain->flags & PD_DMA_OPS_MASK;
1604 }
1605
1606 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1607 {
1608         u64 pte_root = virt_to_phys(domain->pt_root);
1609         u32 flags = 0;
1610
1611         pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1612                     << DEV_ENTRY_MODE_SHIFT;
1613         pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1614
1615         if (ats)
1616                 flags |= DTE_FLAG_IOTLB;
1617
1618         amd_iommu_dev_table[devid].data[3] |= flags;
1619         amd_iommu_dev_table[devid].data[2]  = domain->id;
1620         amd_iommu_dev_table[devid].data[1]  = upper_32_bits(pte_root);
1621         amd_iommu_dev_table[devid].data[0]  = lower_32_bits(pte_root);
1622 }
1623
1624 static void clear_dte_entry(u16 devid)
1625 {
1626         /* remove entry from the device table seen by the hardware */
1627         amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1628         amd_iommu_dev_table[devid].data[1] = 0;
1629         amd_iommu_dev_table[devid].data[2] = 0;
1630
1631         amd_iommu_apply_erratum_63(devid);
1632 }
1633
1634 static void do_attach(struct iommu_dev_data *dev_data,
1635                       struct protection_domain *domain)
1636 {
1637         struct amd_iommu *iommu;
1638         bool ats;
1639
1640         iommu = amd_iommu_rlookup_table[dev_data->devid];
1641         ats   = dev_data->ats.enabled;
1642
1643         /* Update data structures */
1644         dev_data->domain = domain;
1645         list_add(&dev_data->list, &domain->dev_list);
1646         set_dte_entry(dev_data->devid, domain, ats);
1647
1648         /* Do reference counting */
1649         domain->dev_iommu[iommu->index] += 1;
1650         domain->dev_cnt                 += 1;
1651
1652         /* Flush the DTE entry */
1653         device_flush_dte(dev_data);
1654 }
1655
1656 static void do_detach(struct iommu_dev_data *dev_data)
1657 {
1658         struct amd_iommu *iommu;
1659
1660         iommu = amd_iommu_rlookup_table[dev_data->devid];
1661
1662         /* decrease reference counters */
1663         dev_data->domain->dev_iommu[iommu->index] -= 1;
1664         dev_data->domain->dev_cnt                 -= 1;
1665
1666         /* Update data structures */
1667         dev_data->domain = NULL;
1668         list_del(&dev_data->list);
1669         clear_dte_entry(dev_data->devid);
1670
1671         /* Flush the DTE entry */
1672         device_flush_dte(dev_data);
1673 }
1674
1675 /*
1676  * If a device is not yet associated with a domain, this function does
1677  * assigns it visible for the hardware
1678  */
1679 static int __attach_device(struct iommu_dev_data *dev_data,
1680                            struct protection_domain *domain)
1681 {
1682         int ret;
1683
1684         /* lock domain */
1685         spin_lock(&domain->lock);
1686
1687         if (dev_data->alias_data != NULL) {
1688                 struct iommu_dev_data *alias_data = dev_data->alias_data;
1689
1690                 /* Some sanity checks */
1691                 ret = -EBUSY;
1692                 if (alias_data->domain != NULL &&
1693                                 alias_data->domain != domain)
1694                         goto out_unlock;
1695
1696                 if (dev_data->domain != NULL &&
1697                                 dev_data->domain != domain)
1698                         goto out_unlock;
1699
1700                 /* Do real assignment */
1701                 if (alias_data->domain == NULL)
1702                         do_attach(alias_data, domain);
1703
1704                 atomic_inc(&alias_data->bind);
1705         }
1706
1707         if (dev_data->domain == NULL)
1708                 do_attach(dev_data, domain);
1709
1710         atomic_inc(&dev_data->bind);
1711
1712         ret = 0;
1713
1714 out_unlock:
1715
1716         /* ready */
1717         spin_unlock(&domain->lock);
1718
1719         return ret;
1720 }
1721
1722 /*
1723  * If a device is not yet associated with a domain, this function does
1724  * assigns it visible for the hardware
1725  */
1726 static int attach_device(struct device *dev,
1727                          struct protection_domain *domain)
1728 {
1729         struct pci_dev *pdev = to_pci_dev(dev);
1730         struct iommu_dev_data *dev_data;
1731         unsigned long flags;
1732         int ret;
1733
1734         dev_data = get_dev_data(dev);
1735
1736         if (amd_iommu_iotlb_sup && pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
1737                 dev_data->ats.enabled = true;
1738                 dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
1739         }
1740
1741         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1742         ret = __attach_device(dev_data, domain);
1743         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1744
1745         /*
1746          * We might boot into a crash-kernel here. The crashed kernel
1747          * left the caches in the IOMMU dirty. So we have to flush
1748          * here to evict all dirty stuff.
1749          */
1750         domain_flush_tlb_pde(domain);
1751
1752         return ret;
1753 }
1754
1755 /*
1756  * Removes a device from a protection domain (unlocked)
1757  */
1758 static void __detach_device(struct iommu_dev_data *dev_data)
1759 {
1760         struct protection_domain *domain;
1761         unsigned long flags;
1762
1763         BUG_ON(!dev_data->domain);
1764
1765         domain = dev_data->domain;
1766
1767         spin_lock_irqsave(&domain->lock, flags);
1768
1769         if (dev_data->alias_data != NULL) {
1770                 struct iommu_dev_data *alias_data = dev_data->alias_data;
1771
1772                 if (atomic_dec_and_test(&alias_data->bind))
1773                         do_detach(alias_data);
1774         }
1775
1776         if (atomic_dec_and_test(&dev_data->bind))
1777                 do_detach(dev_data);
1778
1779         spin_unlock_irqrestore(&domain->lock, flags);
1780
1781         /*
1782          * If we run in passthrough mode the device must be assigned to the
1783          * passthrough domain if it is detached from any other domain.
1784          * Make sure we can deassign from the pt_domain itself.
1785          */
1786         if (iommu_pass_through &&
1787             (dev_data->domain == NULL && domain != pt_domain))
1788                 __attach_device(dev_data, pt_domain);
1789 }
1790
1791 /*
1792  * Removes a device from a protection domain (with devtable_lock held)
1793  */
1794 static void detach_device(struct device *dev)
1795 {
1796         struct iommu_dev_data *dev_data;
1797         unsigned long flags;
1798
1799         dev_data = get_dev_data(dev);
1800
1801         /* lock device table */
1802         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1803         __detach_device(dev_data);
1804         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1805
1806         if (dev_data->ats.enabled) {
1807                 pci_disable_ats(to_pci_dev(dev));
1808                 dev_data->ats.enabled = false;
1809         }
1810 }
1811
1812 /*
1813  * Find out the protection domain structure for a given PCI device. This
1814  * will give us the pointer to the page table root for example.
1815  */
1816 static struct protection_domain *domain_for_device(struct device *dev)
1817 {
1818         struct iommu_dev_data *dev_data;
1819         struct protection_domain *dom = NULL;
1820         unsigned long flags;
1821
1822         dev_data   = get_dev_data(dev);
1823
1824         if (dev_data->domain)
1825                 return dev_data->domain;
1826
1827         if (dev_data->alias_data != NULL) {
1828                 struct iommu_dev_data *alias_data = dev_data->alias_data;
1829
1830                 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
1831                 if (alias_data->domain != NULL) {
1832                         __attach_device(dev_data, alias_data->domain);
1833                         dom = alias_data->domain;
1834                 }
1835                 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1836         }
1837
1838         return dom;
1839 }
1840
1841 static int device_change_notifier(struct notifier_block *nb,
1842                                   unsigned long action, void *data)
1843 {
1844         struct device *dev = data;
1845         u16 devid;
1846         struct protection_domain *domain;
1847         struct dma_ops_domain *dma_domain;
1848         struct amd_iommu *iommu;
1849         unsigned long flags;
1850
1851         if (!check_device(dev))
1852                 return 0;
1853
1854         devid  = get_device_id(dev);
1855         iommu  = amd_iommu_rlookup_table[devid];
1856
1857         switch (action) {
1858         case BUS_NOTIFY_UNBOUND_DRIVER:
1859
1860                 domain = domain_for_device(dev);
1861
1862                 if (!domain)
1863                         goto out;
1864                 if (iommu_pass_through)
1865                         break;
1866                 detach_device(dev);
1867                 break;
1868         case BUS_NOTIFY_ADD_DEVICE:
1869
1870                 iommu_init_device(dev);
1871
1872                 if (iommu_pass_through) {
1873                         attach_device(dev, pt_domain);
1874                         break;
1875                 }
1876
1877                 domain = domain_for_device(dev);
1878
1879                 /* allocate a protection domain if a device is added */
1880                 dma_domain = find_protection_domain(devid);
1881                 if (!dma_domain) {
1882                         dma_domain = dma_ops_domain_alloc();
1883                         if (!dma_domain)
1884                                 goto out;
1885                         dma_domain->target_dev = devid;
1886
1887                         spin_lock_irqsave(&iommu_pd_list_lock, flags);
1888                         list_add_tail(&dma_domain->list, &iommu_pd_list);
1889                         spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
1890                 }
1891
1892                 dev->archdata.dma_ops = &amd_iommu_dma_ops;
1893
1894                 break;
1895         case BUS_NOTIFY_DEL_DEVICE:
1896
1897                 iommu_uninit_device(dev);
1898
1899         default:
1900                 goto out;
1901         }
1902
1903         iommu_completion_wait(iommu);
1904
1905 out:
1906         return 0;
1907 }
1908
1909 static struct notifier_block device_nb = {
1910         .notifier_call = device_change_notifier,
1911 };
1912
1913 void amd_iommu_init_notifier(void)
1914 {
1915         bus_register_notifier(&pci_bus_type, &device_nb);
1916 }
1917
1918 /*****************************************************************************
1919  *
1920  * The next functions belong to the dma_ops mapping/unmapping code.
1921  *
1922  *****************************************************************************/
1923
1924 /*
1925  * In the dma_ops path we only have the struct device. This function
1926  * finds the corresponding IOMMU, the protection domain and the
1927  * requestor id for a given device.
1928  * If the device is not yet associated with a domain this is also done
1929  * in this function.
1930  */
1931 static struct protection_domain *get_domain(struct device *dev)
1932 {
1933         struct protection_domain *domain;
1934         struct dma_ops_domain *dma_dom;
1935         u16 devid = get_device_id(dev);
1936
1937         if (!check_device(dev))
1938                 return ERR_PTR(-EINVAL);
1939
1940         domain = domain_for_device(dev);
1941         if (domain != NULL && !dma_ops_domain(domain))
1942                 return ERR_PTR(-EBUSY);
1943
1944         if (domain != NULL)
1945                 return domain;
1946
1947         /* Device not bount yet - bind it */
1948         dma_dom = find_protection_domain(devid);
1949         if (!dma_dom)
1950                 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
1951         attach_device(dev, &dma_dom->domain);
1952         DUMP_printk("Using protection domain %d for device %s\n",
1953                     dma_dom->domain.id, dev_name(dev));
1954
1955         return &dma_dom->domain;
1956 }
1957
1958 static void update_device_table(struct protection_domain *domain)
1959 {
1960         struct iommu_dev_data *dev_data;
1961
1962         list_for_each_entry(dev_data, &domain->dev_list, list)
1963                 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
1964 }
1965
1966 static void update_domain(struct protection_domain *domain)
1967 {
1968         if (!domain->updated)
1969                 return;
1970
1971         update_device_table(domain);
1972
1973         domain_flush_devices(domain);
1974         domain_flush_tlb_pde(domain);
1975
1976         domain->updated = false;
1977 }
1978
1979 /*
1980  * This function fetches the PTE for a given address in the aperture
1981  */
1982 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
1983                             unsigned long address)
1984 {
1985         struct aperture_range *aperture;
1986         u64 *pte, *pte_page;
1987
1988         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
1989         if (!aperture)
1990                 return NULL;
1991
1992         pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
1993         if (!pte) {
1994                 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
1995                                 GFP_ATOMIC);
1996                 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
1997         } else
1998                 pte += PM_LEVEL_INDEX(0, address);
1999
2000         update_domain(&dom->domain);
2001
2002         return pte;
2003 }
2004
2005 /*
2006  * This is the generic map function. It maps one 4kb page at paddr to
2007  * the given address in the DMA address space for the domain.
2008  */
2009 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2010                                      unsigned long address,
2011                                      phys_addr_t paddr,
2012                                      int direction)
2013 {
2014         u64 *pte, __pte;
2015
2016         WARN_ON(address > dom->aperture_size);
2017
2018         paddr &= PAGE_MASK;
2019
2020         pte  = dma_ops_get_pte(dom, address);
2021         if (!pte)
2022                 return DMA_ERROR_CODE;
2023
2024         __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2025
2026         if (direction == DMA_TO_DEVICE)
2027                 __pte |= IOMMU_PTE_IR;
2028         else if (direction == DMA_FROM_DEVICE)
2029                 __pte |= IOMMU_PTE_IW;
2030         else if (direction == DMA_BIDIRECTIONAL)
2031                 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2032
2033         WARN_ON(*pte);
2034
2035         *pte = __pte;
2036
2037         return (dma_addr_t)address;
2038 }
2039
2040 /*
2041  * The generic unmapping function for on page in the DMA address space.
2042  */
2043 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2044                                  unsigned long address)
2045 {
2046         struct aperture_range *aperture;
2047         u64 *pte;
2048
2049         if (address >= dom->aperture_size)
2050                 return;
2051
2052         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2053         if (!aperture)
2054                 return;
2055
2056         pte  = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2057         if (!pte)
2058                 return;
2059
2060         pte += PM_LEVEL_INDEX(0, address);
2061
2062         WARN_ON(!*pte);
2063
2064         *pte = 0ULL;
2065 }
2066
2067 /*
2068  * This function contains common code for mapping of a physically
2069  * contiguous memory region into DMA address space. It is used by all
2070  * mapping functions provided with this IOMMU driver.
2071  * Must be called with the domain lock held.
2072  */
2073 static dma_addr_t __map_single(struct device *dev,
2074                                struct dma_ops_domain *dma_dom,
2075                                phys_addr_t paddr,
2076                                size_t size,
2077                                int dir,
2078                                bool align,
2079                                u64 dma_mask)
2080 {
2081         dma_addr_t offset = paddr & ~PAGE_MASK;
2082         dma_addr_t address, start, ret;
2083         unsigned int pages;
2084         unsigned long align_mask = 0;
2085         int i;
2086
2087         pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2088         paddr &= PAGE_MASK;
2089
2090         INC_STATS_COUNTER(total_map_requests);
2091
2092         if (pages > 1)
2093                 INC_STATS_COUNTER(cross_page);
2094
2095         if (align)
2096                 align_mask = (1UL << get_order(size)) - 1;
2097
2098 retry:
2099         address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2100                                           dma_mask);
2101         if (unlikely(address == DMA_ERROR_CODE)) {
2102                 /*
2103                  * setting next_address here will let the address
2104                  * allocator only scan the new allocated range in the
2105                  * first run. This is a small optimization.
2106                  */
2107                 dma_dom->next_address = dma_dom->aperture_size;
2108
2109                 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2110                         goto out;
2111
2112                 /*
2113                  * aperture was successfully enlarged by 128 MB, try
2114                  * allocation again
2115                  */
2116                 goto retry;
2117         }
2118
2119         start = address;
2120         for (i = 0; i < pages; ++i) {
2121                 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2122                 if (ret == DMA_ERROR_CODE)
2123                         goto out_unmap;
2124
2125                 paddr += PAGE_SIZE;
2126                 start += PAGE_SIZE;
2127         }
2128         address += offset;
2129
2130         ADD_STATS_COUNTER(alloced_io_mem, size);
2131
2132         if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2133                 domain_flush_tlb(&dma_dom->domain);
2134                 dma_dom->need_flush = false;
2135         } else if (unlikely(amd_iommu_np_cache))
2136                 domain_flush_pages(&dma_dom->domain, address, size);
2137
2138 out:
2139         return address;
2140
2141 out_unmap:
2142
2143         for (--i; i >= 0; --i) {
2144                 start -= PAGE_SIZE;
2145                 dma_ops_domain_unmap(dma_dom, start);
2146         }
2147
2148         dma_ops_free_addresses(dma_dom, address, pages);
2149
2150         return DMA_ERROR_CODE;
2151 }
2152
2153 /*
2154  * Does the reverse of the __map_single function. Must be called with
2155  * the domain lock held too
2156  */
2157 static void __unmap_single(struct dma_ops_domain *dma_dom,
2158                            dma_addr_t dma_addr,
2159                            size_t size,
2160                            int dir)
2161 {
2162         dma_addr_t flush_addr;
2163         dma_addr_t i, start;
2164         unsigned int pages;
2165
2166         if ((dma_addr == DMA_ERROR_CODE) ||
2167             (dma_addr + size > dma_dom->aperture_size))
2168                 return;
2169
2170         flush_addr = dma_addr;
2171         pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2172         dma_addr &= PAGE_MASK;
2173         start = dma_addr;
2174
2175         for (i = 0; i < pages; ++i) {
2176                 dma_ops_domain_unmap(dma_dom, start);
2177                 start += PAGE_SIZE;
2178         }
2179
2180         SUB_STATS_COUNTER(alloced_io_mem, size);
2181
2182         dma_ops_free_addresses(dma_dom, dma_addr, pages);
2183
2184         if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2185                 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2186                 dma_dom->need_flush = false;
2187         }
2188 }
2189
2190 /*
2191  * The exported map_single function for dma_ops.
2192  */
2193 static dma_addr_t map_page(struct device *dev, struct page *page,
2194                            unsigned long offset, size_t size,
2195                            enum dma_data_direction dir,
2196                            struct dma_attrs *attrs)
2197 {
2198         unsigned long flags;
2199         struct protection_domain *domain;
2200         dma_addr_t addr;
2201         u64 dma_mask;
2202         phys_addr_t paddr = page_to_phys(page) + offset;
2203
2204         INC_STATS_COUNTER(cnt_map_single);
2205
2206         domain = get_domain(dev);
2207         if (PTR_ERR(domain) == -EINVAL)
2208                 return (dma_addr_t)paddr;
2209         else if (IS_ERR(domain))
2210                 return DMA_ERROR_CODE;
2211
2212         dma_mask = *dev->dma_mask;
2213
2214         spin_lock_irqsave(&domain->lock, flags);
2215
2216         addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2217                             dma_mask);
2218         if (addr == DMA_ERROR_CODE)
2219                 goto out;
2220
2221         domain_flush_complete(domain);
2222
2223 out:
2224         spin_unlock_irqrestore(&domain->lock, flags);
2225
2226         return addr;
2227 }
2228
2229 /*
2230  * The exported unmap_single function for dma_ops.
2231  */
2232 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2233                        enum dma_data_direction dir, struct dma_attrs *attrs)
2234 {
2235         unsigned long flags;
2236         struct protection_domain *domain;
2237
2238         INC_STATS_COUNTER(cnt_unmap_single);
2239
2240         domain = get_domain(dev);
2241         if (IS_ERR(domain))
2242                 return;
2243
2244         spin_lock_irqsave(&domain->lock, flags);
2245
2246         __unmap_single(domain->priv, dma_addr, size, dir);
2247
2248         domain_flush_complete(domain);
2249
2250         spin_unlock_irqrestore(&domain->lock, flags);
2251 }
2252
2253 /*
2254  * This is a special map_sg function which is used if we should map a
2255  * device which is not handled by an AMD IOMMU in the system.
2256  */
2257 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2258                            int nelems, int dir)
2259 {
2260         struct scatterlist *s;
2261         int i;
2262
2263         for_each_sg(sglist, s, nelems, i) {
2264                 s->dma_address = (dma_addr_t)sg_phys(s);
2265                 s->dma_length  = s->length;
2266         }
2267
2268         return nelems;
2269 }
2270
2271 /*
2272  * The exported map_sg function for dma_ops (handles scatter-gather
2273  * lists).
2274  */
2275 static int map_sg(struct device *dev, struct scatterlist *sglist,
2276                   int nelems, enum dma_data_direction dir,
2277                   struct dma_attrs *attrs)
2278 {
2279         unsigned long flags;
2280         struct protection_domain *domain;
2281         int i;
2282         struct scatterlist *s;
2283         phys_addr_t paddr;
2284         int mapped_elems = 0;
2285         u64 dma_mask;
2286
2287         INC_STATS_COUNTER(cnt_map_sg);
2288
2289         domain = get_domain(dev);
2290         if (PTR_ERR(domain) == -EINVAL)
2291                 return map_sg_no_iommu(dev, sglist, nelems, dir);
2292         else if (IS_ERR(domain))
2293                 return 0;
2294
2295         dma_mask = *dev->dma_mask;
2296
2297         spin_lock_irqsave(&domain->lock, flags);
2298
2299         for_each_sg(sglist, s, nelems, i) {
2300                 paddr = sg_phys(s);
2301
2302                 s->dma_address = __map_single(dev, domain->priv,
2303                                               paddr, s->length, dir, false,
2304                                               dma_mask);
2305
2306                 if (s->dma_address) {
2307                         s->dma_length = s->length;
2308                         mapped_elems++;
2309                 } else
2310                         goto unmap;
2311         }
2312
2313         domain_flush_complete(domain);
2314
2315 out:
2316         spin_unlock_irqrestore(&domain->lock, flags);
2317
2318         return mapped_elems;
2319 unmap:
2320         for_each_sg(sglist, s, mapped_elems, i) {
2321                 if (s->dma_address)
2322                         __unmap_single(domain->priv, s->dma_address,
2323                                        s->dma_length, dir);
2324                 s->dma_address = s->dma_length = 0;
2325         }
2326
2327         mapped_elems = 0;
2328
2329         goto out;
2330 }
2331
2332 /*
2333  * The exported map_sg function for dma_ops (handles scatter-gather
2334  * lists).
2335  */
2336 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2337                      int nelems, enum dma_data_direction dir,
2338                      struct dma_attrs *attrs)
2339 {
2340         unsigned long flags;
2341         struct protection_domain *domain;
2342         struct scatterlist *s;
2343         int i;
2344
2345         INC_STATS_COUNTER(cnt_unmap_sg);
2346
2347         domain = get_domain(dev);
2348         if (IS_ERR(domain))
2349                 return;
2350
2351         spin_lock_irqsave(&domain->lock, flags);
2352
2353         for_each_sg(sglist, s, nelems, i) {
2354                 __unmap_single(domain->priv, s->dma_address,
2355                                s->dma_length, dir);
2356                 s->dma_address = s->dma_length = 0;
2357         }
2358
2359         domain_flush_complete(domain);
2360
2361         spin_unlock_irqrestore(&domain->lock, flags);
2362 }
2363
2364 /*
2365  * The exported alloc_coherent function for dma_ops.
2366  */
2367 static void *alloc_coherent(struct device *dev, size_t size,
2368                             dma_addr_t *dma_addr, gfp_t flag)
2369 {
2370         unsigned long flags;
2371         void *virt_addr;
2372         struct protection_domain *domain;
2373         phys_addr_t paddr;
2374         u64 dma_mask = dev->coherent_dma_mask;
2375
2376         INC_STATS_COUNTER(cnt_alloc_coherent);
2377
2378         domain = get_domain(dev);
2379         if (PTR_ERR(domain) == -EINVAL) {
2380                 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2381                 *dma_addr = __pa(virt_addr);
2382                 return virt_addr;
2383         } else if (IS_ERR(domain))
2384                 return NULL;
2385
2386         dma_mask  = dev->coherent_dma_mask;
2387         flag     &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2388         flag     |= __GFP_ZERO;
2389
2390         virt_addr = (void *)__get_free_pages(flag, get_order(size));
2391         if (!virt_addr)
2392                 return NULL;
2393
2394         paddr = virt_to_phys(virt_addr);
2395
2396         if (!dma_mask)
2397                 dma_mask = *dev->dma_mask;
2398
2399         spin_lock_irqsave(&domain->lock, flags);
2400
2401         *dma_addr = __map_single(dev, domain->priv, paddr,
2402                                  size, DMA_BIDIRECTIONAL, true, dma_mask);
2403
2404         if (*dma_addr == DMA_ERROR_CODE) {
2405                 spin_unlock_irqrestore(&domain->lock, flags);
2406                 goto out_free;
2407         }
2408
2409         domain_flush_complete(domain);
2410
2411         spin_unlock_irqrestore(&domain->lock, flags);
2412
2413         return virt_addr;
2414
2415 out_free:
2416
2417         free_pages((unsigned long)virt_addr, get_order(size));
2418
2419         return NULL;
2420 }
2421
2422 /*
2423  * The exported free_coherent function for dma_ops.
2424  */
2425 static void free_coherent(struct device *dev, size_t size,
2426                           void *virt_addr, dma_addr_t dma_addr)
2427 {
2428         unsigned long flags;
2429         struct protection_domain *domain;
2430
2431         INC_STATS_COUNTER(cnt_free_coherent);
2432
2433         domain = get_domain(dev);
2434         if (IS_ERR(domain))
2435                 goto free_mem;
2436
2437         spin_lock_irqsave(&domain->lock, flags);
2438
2439         __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2440
2441         domain_flush_complete(domain);
2442
2443         spin_unlock_irqrestore(&domain->lock, flags);
2444
2445 free_mem:
2446         free_pages((unsigned long)virt_addr, get_order(size));
2447 }
2448
2449 /*
2450  * This function is called by the DMA layer to find out if we can handle a
2451  * particular device. It is part of the dma_ops.
2452  */
2453 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2454 {
2455         return check_device(dev);
2456 }
2457
2458 /*
2459  * The function for pre-allocating protection domains.
2460  *
2461  * If the driver core informs the DMA layer if a driver grabs a device
2462  * we don't need to preallocate the protection domains anymore.
2463  * For now we have to.
2464  */
2465 static void __init prealloc_protection_domains(void)
2466 {
2467         struct pci_dev *dev = NULL;
2468         struct dma_ops_domain *dma_dom;
2469         u16 devid;
2470
2471         for_each_pci_dev(dev) {
2472
2473                 /* Do we handle this device? */
2474                 if (!check_device(&dev->dev))
2475                         continue;
2476
2477                 /* Is there already any domain for it? */
2478                 if (domain_for_device(&dev->dev))
2479                         continue;
2480
2481                 devid = get_device_id(&dev->dev);
2482
2483                 dma_dom = dma_ops_domain_alloc();
2484                 if (!dma_dom)
2485                         continue;
2486                 init_unity_mappings_for_device(dma_dom, devid);
2487                 dma_dom->target_dev = devid;
2488
2489                 attach_device(&dev->dev, &dma_dom->domain);
2490
2491                 list_add_tail(&dma_dom->list, &iommu_pd_list);
2492         }
2493 }
2494
2495 static struct dma_map_ops amd_iommu_dma_ops = {
2496         .alloc_coherent = alloc_coherent,
2497         .free_coherent = free_coherent,
2498         .map_page = map_page,
2499         .unmap_page = unmap_page,
2500         .map_sg = map_sg,
2501         .unmap_sg = unmap_sg,
2502         .dma_supported = amd_iommu_dma_supported,
2503 };
2504
2505 static unsigned device_dma_ops_init(void)
2506 {
2507         struct pci_dev *pdev = NULL;
2508         unsigned unhandled = 0;
2509
2510         for_each_pci_dev(pdev) {
2511                 if (!check_device(&pdev->dev)) {
2512
2513                         iommu_ignore_device(&pdev->dev);
2514
2515                         unhandled += 1;
2516                         continue;
2517                 }
2518
2519                 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
2520         }
2521
2522         return unhandled;
2523 }
2524
2525 /*
2526  * The function which clues the AMD IOMMU driver into dma_ops.
2527  */
2528
2529 void __init amd_iommu_init_api(void)
2530 {
2531         bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2532 }
2533
2534 int __init amd_iommu_init_dma_ops(void)
2535 {
2536         struct amd_iommu *iommu;
2537         int ret, unhandled;
2538
2539         /*
2540          * first allocate a default protection domain for every IOMMU we
2541          * found in the system. Devices not assigned to any other
2542          * protection domain will be assigned to the default one.
2543          */
2544         for_each_iommu(iommu) {
2545                 iommu->default_dom = dma_ops_domain_alloc();
2546                 if (iommu->default_dom == NULL)
2547                         return -ENOMEM;
2548                 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
2549                 ret = iommu_init_unity_mappings(iommu);
2550                 if (ret)
2551                         goto free_domains;
2552         }
2553
2554         /*
2555          * Pre-allocate the protection domains for each device.
2556          */
2557         prealloc_protection_domains();
2558
2559         iommu_detected = 1;
2560         swiotlb = 0;
2561
2562         /* Make the driver finally visible to the drivers */
2563         unhandled = device_dma_ops_init();
2564         if (unhandled && max_pfn > MAX_DMA32_PFN) {
2565                 /* There are unhandled devices - initialize swiotlb for them */
2566                 swiotlb = 1;
2567         }
2568
2569         amd_iommu_stats_init();
2570
2571         return 0;
2572
2573 free_domains:
2574
2575         for_each_iommu(iommu) {
2576                 if (iommu->default_dom)
2577                         dma_ops_domain_free(iommu->default_dom);
2578         }
2579
2580         return ret;
2581 }
2582
2583 /*****************************************************************************
2584  *
2585  * The following functions belong to the exported interface of AMD IOMMU
2586  *
2587  * This interface allows access to lower level functions of the IOMMU
2588  * like protection domain handling and assignement of devices to domains
2589  * which is not possible with the dma_ops interface.
2590  *
2591  *****************************************************************************/
2592
2593 static void cleanup_domain(struct protection_domain *domain)
2594 {
2595         struct iommu_dev_data *entry;
2596         unsigned long flags;
2597
2598         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2599
2600         while (!list_empty(&domain->dev_list)) {
2601                 entry = list_first_entry(&domain->dev_list,
2602                                          struct iommu_dev_data, list);
2603                 __detach_device(entry);
2604                 atomic_set(&entry->bind, 0);
2605         }
2606
2607         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2608 }
2609
2610 static void protection_domain_free(struct protection_domain *domain)
2611 {
2612         if (!domain)
2613                 return;
2614
2615         del_domain_from_list(domain);
2616
2617         if (domain->id)
2618                 domain_id_free(domain->id);
2619
2620         kfree(domain);
2621 }
2622
2623 static struct protection_domain *protection_domain_alloc(void)
2624 {
2625         struct protection_domain *domain;
2626
2627         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2628         if (!domain)
2629                 return NULL;
2630
2631         spin_lock_init(&domain->lock);
2632         mutex_init(&domain->api_lock);
2633         domain->id = domain_id_alloc();
2634         if (!domain->id)
2635                 goto out_err;
2636         INIT_LIST_HEAD(&domain->dev_list);
2637
2638         add_domain_to_list(domain);
2639
2640         return domain;
2641
2642 out_err:
2643         kfree(domain);
2644
2645         return NULL;
2646 }
2647
2648 static int amd_iommu_domain_init(struct iommu_domain *dom)
2649 {
2650         struct protection_domain *domain;
2651
2652         domain = protection_domain_alloc();
2653         if (!domain)
2654                 goto out_free;
2655
2656         domain->mode    = PAGE_MODE_3_LEVEL;
2657         domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2658         if (!domain->pt_root)
2659                 goto out_free;
2660
2661         dom->priv = domain;
2662
2663         return 0;
2664
2665 out_free:
2666         protection_domain_free(domain);
2667
2668         return -ENOMEM;
2669 }
2670
2671 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
2672 {
2673         struct protection_domain *domain = dom->priv;
2674
2675         if (!domain)
2676                 return;
2677
2678         if (domain->dev_cnt > 0)
2679                 cleanup_domain(domain);
2680
2681         BUG_ON(domain->dev_cnt != 0);
2682
2683         free_pagetable(domain);
2684
2685         protection_domain_free(domain);
2686
2687         dom->priv = NULL;
2688 }
2689
2690 static void amd_iommu_detach_device(struct iommu_domain *dom,
2691                                     struct device *dev)
2692 {
2693         struct iommu_dev_data *dev_data = dev->archdata.iommu;
2694         struct amd_iommu *iommu;
2695         u16 devid;
2696
2697         if (!check_device(dev))
2698                 return;
2699
2700         devid = get_device_id(dev);
2701
2702         if (dev_data->domain != NULL)
2703                 detach_device(dev);
2704
2705         iommu = amd_iommu_rlookup_table[devid];
2706         if (!iommu)
2707                 return;
2708
2709         iommu_completion_wait(iommu);
2710 }
2711
2712 static int amd_iommu_attach_device(struct iommu_domain *dom,
2713                                    struct device *dev)
2714 {
2715         struct protection_domain *domain = dom->priv;
2716         struct iommu_dev_data *dev_data;
2717         struct amd_iommu *iommu;
2718         int ret;
2719
2720         if (!check_device(dev))
2721                 return -EINVAL;
2722
2723         dev_data = dev->archdata.iommu;
2724
2725         iommu = amd_iommu_rlookup_table[dev_data->devid];
2726         if (!iommu)
2727                 return -EINVAL;
2728
2729         if (dev_data->domain)
2730                 detach_device(dev);
2731
2732         ret = attach_device(dev, domain);
2733
2734         iommu_completion_wait(iommu);
2735
2736         return ret;
2737 }
2738
2739 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
2740                          phys_addr_t paddr, int gfp_order, int iommu_prot)
2741 {
2742         unsigned long page_size = 0x1000UL << gfp_order;
2743         struct protection_domain *domain = dom->priv;
2744         int prot = 0;
2745         int ret;
2746
2747         if (iommu_prot & IOMMU_READ)
2748                 prot |= IOMMU_PROT_IR;
2749         if (iommu_prot & IOMMU_WRITE)
2750                 prot |= IOMMU_PROT_IW;
2751
2752         mutex_lock(&domain->api_lock);
2753         ret = iommu_map_page(domain, iova, paddr, prot, page_size);
2754         mutex_unlock(&domain->api_lock);
2755
2756         return ret;
2757 }
2758
2759 static int amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
2760                            int gfp_order)
2761 {
2762         struct protection_domain *domain = dom->priv;
2763         unsigned long page_size, unmap_size;
2764
2765         page_size  = 0x1000UL << gfp_order;
2766
2767         mutex_lock(&domain->api_lock);
2768         unmap_size = iommu_unmap_page(domain, iova, page_size);
2769         mutex_unlock(&domain->api_lock);
2770
2771         domain_flush_tlb_pde(domain);
2772
2773         return get_order(unmap_size);
2774 }
2775
2776 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
2777                                           unsigned long iova)
2778 {
2779         struct protection_domain *domain = dom->priv;
2780         unsigned long offset_mask;
2781         phys_addr_t paddr;
2782         u64 *pte, __pte;
2783
2784         pte = fetch_pte(domain, iova);
2785
2786         if (!pte || !IOMMU_PTE_PRESENT(*pte))
2787                 return 0;
2788
2789         if (PM_PTE_LEVEL(*pte) == 0)
2790                 offset_mask = PAGE_SIZE - 1;
2791         else
2792                 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
2793
2794         __pte = *pte & PM_ADDR_MASK;
2795         paddr = (__pte & ~offset_mask) | (iova & offset_mask);
2796
2797         return paddr;
2798 }
2799
2800 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
2801                                     unsigned long cap)
2802 {
2803         switch (cap) {
2804         case IOMMU_CAP_CACHE_COHERENCY:
2805                 return 1;
2806         }
2807
2808         return 0;
2809 }
2810
2811 static struct iommu_ops amd_iommu_ops = {
2812         .domain_init = amd_iommu_domain_init,
2813         .domain_destroy = amd_iommu_domain_destroy,
2814         .attach_dev = amd_iommu_attach_device,
2815         .detach_dev = amd_iommu_detach_device,
2816         .map = amd_iommu_map,
2817         .unmap = amd_iommu_unmap,
2818         .iova_to_phys = amd_iommu_iova_to_phys,
2819         .domain_has_cap = amd_iommu_domain_has_cap,
2820 };
2821
2822 /*****************************************************************************
2823  *
2824  * The next functions do a basic initialization of IOMMU for pass through
2825  * mode
2826  *
2827  * In passthrough mode the IOMMU is initialized and enabled but not used for
2828  * DMA-API translation.
2829  *
2830  *****************************************************************************/
2831
2832 int __init amd_iommu_init_passthrough(void)
2833 {
2834         struct amd_iommu *iommu;
2835         struct pci_dev *dev = NULL;
2836         u16 devid;
2837
2838         /* allocate passthrough domain */
2839         pt_domain = protection_domain_alloc();
2840         if (!pt_domain)
2841                 return -ENOMEM;
2842
2843         pt_domain->mode |= PAGE_MODE_NONE;
2844
2845         for_each_pci_dev(dev) {
2846                 if (!check_device(&dev->dev))
2847                         continue;
2848
2849                 devid = get_device_id(&dev->dev);
2850
2851                 iommu = amd_iommu_rlookup_table[devid];
2852                 if (!iommu)
2853                         continue;
2854
2855                 attach_device(&dev->dev, pt_domain);
2856         }
2857
2858         pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
2859
2860         return 0;
2861 }