mm: thp: set the accessed flag for old pages on access fault
[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                         count      = PAGE_SIZE_PTE_COUNT(unmap_size);
1080                         for (i = 0; i < count; i++)
1081                                 pte[i] = 0ULL;
1082                 }
1083
1084                 bus_addr  = (bus_addr & ~(unmap_size - 1)) + unmap_size;
1085                 unmapped += unmap_size;
1086         }
1087
1088         BUG_ON(!is_power_of_2(unmapped));
1089
1090         return unmapped;
1091 }
1092
1093 /*
1094  * This function checks if a specific unity mapping entry is needed for
1095  * this specific IOMMU.
1096  */
1097 static int iommu_for_unity_map(struct amd_iommu *iommu,
1098                                struct unity_map_entry *entry)
1099 {
1100         u16 bdf, i;
1101
1102         for (i = entry->devid_start; i <= entry->devid_end; ++i) {
1103                 bdf = amd_iommu_alias_table[i];
1104                 if (amd_iommu_rlookup_table[bdf] == iommu)
1105                         return 1;
1106         }
1107
1108         return 0;
1109 }
1110
1111 /*
1112  * This function actually applies the mapping to the page table of the
1113  * dma_ops domain.
1114  */
1115 static int dma_ops_unity_map(struct dma_ops_domain *dma_dom,
1116                              struct unity_map_entry *e)
1117 {
1118         u64 addr;
1119         int ret;
1120
1121         for (addr = e->address_start; addr < e->address_end;
1122              addr += PAGE_SIZE) {
1123                 ret = iommu_map_page(&dma_dom->domain, addr, addr, e->prot,
1124                                      PAGE_SIZE);
1125                 if (ret)
1126                         return ret;
1127                 /*
1128                  * if unity mapping is in aperture range mark the page
1129                  * as allocated in the aperture
1130                  */
1131                 if (addr < dma_dom->aperture_size)
1132                         __set_bit(addr >> PAGE_SHIFT,
1133                                   dma_dom->aperture[0]->bitmap);
1134         }
1135
1136         return 0;
1137 }
1138
1139 /*
1140  * Init the unity mappings for a specific IOMMU in the system
1141  *
1142  * Basically iterates over all unity mapping entries and applies them to
1143  * the default domain DMA of that IOMMU if necessary.
1144  */
1145 static int iommu_init_unity_mappings(struct amd_iommu *iommu)
1146 {
1147         struct unity_map_entry *entry;
1148         int ret;
1149
1150         list_for_each_entry(entry, &amd_iommu_unity_map, list) {
1151                 if (!iommu_for_unity_map(iommu, entry))
1152                         continue;
1153                 ret = dma_ops_unity_map(iommu->default_dom, entry);
1154                 if (ret)
1155                         return ret;
1156         }
1157
1158         return 0;
1159 }
1160
1161 /*
1162  * Inits the unity mappings required for a specific device
1163  */
1164 static int init_unity_mappings_for_device(struct dma_ops_domain *dma_dom,
1165                                           u16 devid)
1166 {
1167         struct unity_map_entry *e;
1168         int ret;
1169
1170         list_for_each_entry(e, &amd_iommu_unity_map, list) {
1171                 if (!(devid >= e->devid_start && devid <= e->devid_end))
1172                         continue;
1173                 ret = dma_ops_unity_map(dma_dom, e);
1174                 if (ret)
1175                         return ret;
1176         }
1177
1178         return 0;
1179 }
1180
1181 /****************************************************************************
1182  *
1183  * The next functions belong to the address allocator for the dma_ops
1184  * interface functions. They work like the allocators in the other IOMMU
1185  * drivers. Its basically a bitmap which marks the allocated pages in
1186  * the aperture. Maybe it could be enhanced in the future to a more
1187  * efficient allocator.
1188  *
1189  ****************************************************************************/
1190
1191 /*
1192  * The address allocator core functions.
1193  *
1194  * called with domain->lock held
1195  */
1196
1197 /*
1198  * Used to reserve address ranges in the aperture (e.g. for exclusion
1199  * ranges.
1200  */
1201 static void dma_ops_reserve_addresses(struct dma_ops_domain *dom,
1202                                       unsigned long start_page,
1203                                       unsigned int pages)
1204 {
1205         unsigned int i, last_page = dom->aperture_size >> PAGE_SHIFT;
1206
1207         if (start_page + pages > last_page)
1208                 pages = last_page - start_page;
1209
1210         for (i = start_page; i < start_page + pages; ++i) {
1211                 int index = i / APERTURE_RANGE_PAGES;
1212                 int page  = i % APERTURE_RANGE_PAGES;
1213                 __set_bit(page, dom->aperture[index]->bitmap);
1214         }
1215 }
1216
1217 /*
1218  * This function is used to add a new aperture range to an existing
1219  * aperture in case of dma_ops domain allocation or address allocation
1220  * failure.
1221  */
1222 static int alloc_new_range(struct dma_ops_domain *dma_dom,
1223                            bool populate, gfp_t gfp)
1224 {
1225         int index = dma_dom->aperture_size >> APERTURE_RANGE_SHIFT;
1226         struct amd_iommu *iommu;
1227         unsigned long i, old_size;
1228
1229 #ifdef CONFIG_IOMMU_STRESS
1230         populate = false;
1231 #endif
1232
1233         if (index >= APERTURE_MAX_RANGES)
1234                 return -ENOMEM;
1235
1236         dma_dom->aperture[index] = kzalloc(sizeof(struct aperture_range), gfp);
1237         if (!dma_dom->aperture[index])
1238                 return -ENOMEM;
1239
1240         dma_dom->aperture[index]->bitmap = (void *)get_zeroed_page(gfp);
1241         if (!dma_dom->aperture[index]->bitmap)
1242                 goto out_free;
1243
1244         dma_dom->aperture[index]->offset = dma_dom->aperture_size;
1245
1246         if (populate) {
1247                 unsigned long address = dma_dom->aperture_size;
1248                 int i, num_ptes = APERTURE_RANGE_PAGES / 512;
1249                 u64 *pte, *pte_page;
1250
1251                 for (i = 0; i < num_ptes; ++i) {
1252                         pte = alloc_pte(&dma_dom->domain, address, PAGE_SIZE,
1253                                         &pte_page, gfp);
1254                         if (!pte)
1255                                 goto out_free;
1256
1257                         dma_dom->aperture[index]->pte_pages[i] = pte_page;
1258
1259                         address += APERTURE_RANGE_SIZE / 64;
1260                 }
1261         }
1262
1263         old_size                = dma_dom->aperture_size;
1264         dma_dom->aperture_size += APERTURE_RANGE_SIZE;
1265
1266         /* Reserve address range used for MSI messages */
1267         if (old_size < MSI_ADDR_BASE_LO &&
1268             dma_dom->aperture_size > MSI_ADDR_BASE_LO) {
1269                 unsigned long spage;
1270                 int pages;
1271
1272                 pages = iommu_num_pages(MSI_ADDR_BASE_LO, 0x10000, PAGE_SIZE);
1273                 spage = MSI_ADDR_BASE_LO >> PAGE_SHIFT;
1274
1275                 dma_ops_reserve_addresses(dma_dom, spage, pages);
1276         }
1277
1278         /* Initialize the exclusion range if necessary */
1279         for_each_iommu(iommu) {
1280                 if (iommu->exclusion_start &&
1281                     iommu->exclusion_start >= dma_dom->aperture[index]->offset
1282                     && iommu->exclusion_start < dma_dom->aperture_size) {
1283                         unsigned long startpage;
1284                         int pages = iommu_num_pages(iommu->exclusion_start,
1285                                                     iommu->exclusion_length,
1286                                                     PAGE_SIZE);
1287                         startpage = iommu->exclusion_start >> PAGE_SHIFT;
1288                         dma_ops_reserve_addresses(dma_dom, startpage, pages);
1289                 }
1290         }
1291
1292         /*
1293          * Check for areas already mapped as present in the new aperture
1294          * range and mark those pages as reserved in the allocator. Such
1295          * mappings may already exist as a result of requested unity
1296          * mappings for devices.
1297          */
1298         for (i = dma_dom->aperture[index]->offset;
1299              i < dma_dom->aperture_size;
1300              i += PAGE_SIZE) {
1301                 u64 *pte = fetch_pte(&dma_dom->domain, i);
1302                 if (!pte || !IOMMU_PTE_PRESENT(*pte))
1303                         continue;
1304
1305                 dma_ops_reserve_addresses(dma_dom, i >> PAGE_SHIFT, 1);
1306         }
1307
1308         update_domain(&dma_dom->domain);
1309
1310         return 0;
1311
1312 out_free:
1313         update_domain(&dma_dom->domain);
1314
1315         free_page((unsigned long)dma_dom->aperture[index]->bitmap);
1316
1317         kfree(dma_dom->aperture[index]);
1318         dma_dom->aperture[index] = NULL;
1319
1320         return -ENOMEM;
1321 }
1322
1323 static unsigned long dma_ops_area_alloc(struct device *dev,
1324                                         struct dma_ops_domain *dom,
1325                                         unsigned int pages,
1326                                         unsigned long align_mask,
1327                                         u64 dma_mask,
1328                                         unsigned long start)
1329 {
1330         unsigned long next_bit = dom->next_address % APERTURE_RANGE_SIZE;
1331         int max_index = dom->aperture_size >> APERTURE_RANGE_SHIFT;
1332         int i = start >> APERTURE_RANGE_SHIFT;
1333         unsigned long boundary_size;
1334         unsigned long address = -1;
1335         unsigned long limit;
1336
1337         next_bit >>= PAGE_SHIFT;
1338
1339         boundary_size = ALIGN(dma_get_seg_boundary(dev) + 1,
1340                         PAGE_SIZE) >> PAGE_SHIFT;
1341
1342         for (;i < max_index; ++i) {
1343                 unsigned long offset = dom->aperture[i]->offset >> PAGE_SHIFT;
1344
1345                 if (dom->aperture[i]->offset >= dma_mask)
1346                         break;
1347
1348                 limit = iommu_device_max_index(APERTURE_RANGE_PAGES, offset,
1349                                                dma_mask >> PAGE_SHIFT);
1350
1351                 address = iommu_area_alloc(dom->aperture[i]->bitmap,
1352                                            limit, next_bit, pages, 0,
1353                                             boundary_size, align_mask);
1354                 if (address != -1) {
1355                         address = dom->aperture[i]->offset +
1356                                   (address << PAGE_SHIFT);
1357                         dom->next_address = address + (pages << PAGE_SHIFT);
1358                         break;
1359                 }
1360
1361                 next_bit = 0;
1362         }
1363
1364         return address;
1365 }
1366
1367 static unsigned long dma_ops_alloc_addresses(struct device *dev,
1368                                              struct dma_ops_domain *dom,
1369                                              unsigned int pages,
1370                                              unsigned long align_mask,
1371                                              u64 dma_mask)
1372 {
1373         unsigned long address;
1374
1375 #ifdef CONFIG_IOMMU_STRESS
1376         dom->next_address = 0;
1377         dom->need_flush = true;
1378 #endif
1379
1380         address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1381                                      dma_mask, dom->next_address);
1382
1383         if (address == -1) {
1384                 dom->next_address = 0;
1385                 address = dma_ops_area_alloc(dev, dom, pages, align_mask,
1386                                              dma_mask, 0);
1387                 dom->need_flush = true;
1388         }
1389
1390         if (unlikely(address == -1))
1391                 address = DMA_ERROR_CODE;
1392
1393         WARN_ON((address + (PAGE_SIZE*pages)) > dom->aperture_size);
1394
1395         return address;
1396 }
1397
1398 /*
1399  * The address free function.
1400  *
1401  * called with domain->lock held
1402  */
1403 static void dma_ops_free_addresses(struct dma_ops_domain *dom,
1404                                    unsigned long address,
1405                                    unsigned int pages)
1406 {
1407         unsigned i = address >> APERTURE_RANGE_SHIFT;
1408         struct aperture_range *range = dom->aperture[i];
1409
1410         BUG_ON(i >= APERTURE_MAX_RANGES || range == NULL);
1411
1412 #ifdef CONFIG_IOMMU_STRESS
1413         if (i < 4)
1414                 return;
1415 #endif
1416
1417         if (address >= dom->next_address)
1418                 dom->need_flush = true;
1419
1420         address = (address % APERTURE_RANGE_SIZE) >> PAGE_SHIFT;
1421
1422         bitmap_clear(range->bitmap, address, pages);
1423
1424 }
1425
1426 /****************************************************************************
1427  *
1428  * The next functions belong to the domain allocation. A domain is
1429  * allocated for every IOMMU as the default domain. If device isolation
1430  * is enabled, every device get its own domain. The most important thing
1431  * about domains is the page table mapping the DMA address space they
1432  * contain.
1433  *
1434  ****************************************************************************/
1435
1436 /*
1437  * This function adds a protection domain to the global protection domain list
1438  */
1439 static void add_domain_to_list(struct protection_domain *domain)
1440 {
1441         unsigned long flags;
1442
1443         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1444         list_add(&domain->list, &amd_iommu_pd_list);
1445         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1446 }
1447
1448 /*
1449  * This function removes a protection domain to the global
1450  * protection domain list
1451  */
1452 static void del_domain_from_list(struct protection_domain *domain)
1453 {
1454         unsigned long flags;
1455
1456         spin_lock_irqsave(&amd_iommu_pd_lock, flags);
1457         list_del(&domain->list);
1458         spin_unlock_irqrestore(&amd_iommu_pd_lock, flags);
1459 }
1460
1461 static u16 domain_id_alloc(void)
1462 {
1463         unsigned long flags;
1464         int id;
1465
1466         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1467         id = find_first_zero_bit(amd_iommu_pd_alloc_bitmap, MAX_DOMAIN_ID);
1468         BUG_ON(id == 0);
1469         if (id > 0 && id < MAX_DOMAIN_ID)
1470                 __set_bit(id, amd_iommu_pd_alloc_bitmap);
1471         else
1472                 id = 0;
1473         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1474
1475         return id;
1476 }
1477
1478 static void domain_id_free(int id)
1479 {
1480         unsigned long flags;
1481
1482         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1483         if (id > 0 && id < MAX_DOMAIN_ID)
1484                 __clear_bit(id, amd_iommu_pd_alloc_bitmap);
1485         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1486 }
1487
1488 static void free_pagetable(struct protection_domain *domain)
1489 {
1490         int i, j;
1491         u64 *p1, *p2, *p3;
1492
1493         p1 = domain->pt_root;
1494
1495         if (!p1)
1496                 return;
1497
1498         for (i = 0; i < 512; ++i) {
1499                 if (!IOMMU_PTE_PRESENT(p1[i]))
1500                         continue;
1501
1502                 p2 = IOMMU_PTE_PAGE(p1[i]);
1503                 for (j = 0; j < 512; ++j) {
1504                         if (!IOMMU_PTE_PRESENT(p2[j]))
1505                                 continue;
1506                         p3 = IOMMU_PTE_PAGE(p2[j]);
1507                         free_page((unsigned long)p3);
1508                 }
1509
1510                 free_page((unsigned long)p2);
1511         }
1512
1513         free_page((unsigned long)p1);
1514
1515         domain->pt_root = NULL;
1516 }
1517
1518 /*
1519  * Free a domain, only used if something went wrong in the
1520  * allocation path and we need to free an already allocated page table
1521  */
1522 static void dma_ops_domain_free(struct dma_ops_domain *dom)
1523 {
1524         int i;
1525
1526         if (!dom)
1527                 return;
1528
1529         del_domain_from_list(&dom->domain);
1530
1531         free_pagetable(&dom->domain);
1532
1533         for (i = 0; i < APERTURE_MAX_RANGES; ++i) {
1534                 if (!dom->aperture[i])
1535                         continue;
1536                 free_page((unsigned long)dom->aperture[i]->bitmap);
1537                 kfree(dom->aperture[i]);
1538         }
1539
1540         kfree(dom);
1541 }
1542
1543 /*
1544  * Allocates a new protection domain usable for the dma_ops functions.
1545  * It also initializes the page table and the address allocator data
1546  * structures required for the dma_ops interface
1547  */
1548 static struct dma_ops_domain *dma_ops_domain_alloc(void)
1549 {
1550         struct dma_ops_domain *dma_dom;
1551
1552         dma_dom = kzalloc(sizeof(struct dma_ops_domain), GFP_KERNEL);
1553         if (!dma_dom)
1554                 return NULL;
1555
1556         spin_lock_init(&dma_dom->domain.lock);
1557
1558         dma_dom->domain.id = domain_id_alloc();
1559         if (dma_dom->domain.id == 0)
1560                 goto free_dma_dom;
1561         INIT_LIST_HEAD(&dma_dom->domain.dev_list);
1562         dma_dom->domain.mode = PAGE_MODE_2_LEVEL;
1563         dma_dom->domain.pt_root = (void *)get_zeroed_page(GFP_KERNEL);
1564         dma_dom->domain.flags = PD_DMA_OPS_MASK;
1565         dma_dom->domain.priv = dma_dom;
1566         if (!dma_dom->domain.pt_root)
1567                 goto free_dma_dom;
1568
1569         dma_dom->need_flush = false;
1570         dma_dom->target_dev = 0xffff;
1571
1572         add_domain_to_list(&dma_dom->domain);
1573
1574         if (alloc_new_range(dma_dom, true, GFP_KERNEL))
1575                 goto free_dma_dom;
1576
1577         /*
1578          * mark the first page as allocated so we never return 0 as
1579          * a valid dma-address. So we can use 0 as error value
1580          */
1581         dma_dom->aperture[0]->bitmap[0] = 1;
1582         dma_dom->next_address = 0;
1583
1584
1585         return dma_dom;
1586
1587 free_dma_dom:
1588         dma_ops_domain_free(dma_dom);
1589
1590         return NULL;
1591 }
1592
1593 /*
1594  * little helper function to check whether a given protection domain is a
1595  * dma_ops domain
1596  */
1597 static bool dma_ops_domain(struct protection_domain *domain)
1598 {
1599         return domain->flags & PD_DMA_OPS_MASK;
1600 }
1601
1602 static void set_dte_entry(u16 devid, struct protection_domain *domain, bool ats)
1603 {
1604         u64 pte_root = virt_to_phys(domain->pt_root);
1605         u32 flags = 0;
1606
1607         pte_root |= (domain->mode & DEV_ENTRY_MODE_MASK)
1608                     << DEV_ENTRY_MODE_SHIFT;
1609         pte_root |= IOMMU_PTE_IR | IOMMU_PTE_IW | IOMMU_PTE_P | IOMMU_PTE_TV;
1610
1611         if (ats)
1612                 flags |= DTE_FLAG_IOTLB;
1613
1614         amd_iommu_dev_table[devid].data[3] |= flags;
1615         amd_iommu_dev_table[devid].data[2]  = domain->id;
1616         amd_iommu_dev_table[devid].data[1]  = upper_32_bits(pte_root);
1617         amd_iommu_dev_table[devid].data[0]  = lower_32_bits(pte_root);
1618 }
1619
1620 static void clear_dte_entry(u16 devid)
1621 {
1622         /* remove entry from the device table seen by the hardware */
1623         amd_iommu_dev_table[devid].data[0] = IOMMU_PTE_P | IOMMU_PTE_TV;
1624         amd_iommu_dev_table[devid].data[1] = 0;
1625         amd_iommu_dev_table[devid].data[2] = 0;
1626
1627         amd_iommu_apply_erratum_63(devid);
1628 }
1629
1630 static void do_attach(struct iommu_dev_data *dev_data,
1631                       struct protection_domain *domain)
1632 {
1633         struct amd_iommu *iommu;
1634         bool ats;
1635
1636         iommu = amd_iommu_rlookup_table[dev_data->devid];
1637         ats   = dev_data->ats.enabled;
1638
1639         /* Update data structures */
1640         dev_data->domain = domain;
1641         list_add(&dev_data->list, &domain->dev_list);
1642         set_dte_entry(dev_data->devid, domain, ats);
1643
1644         /* Do reference counting */
1645         domain->dev_iommu[iommu->index] += 1;
1646         domain->dev_cnt                 += 1;
1647
1648         /* Flush the DTE entry */
1649         device_flush_dte(dev_data);
1650 }
1651
1652 static void do_detach(struct iommu_dev_data *dev_data)
1653 {
1654         struct amd_iommu *iommu;
1655
1656         iommu = amd_iommu_rlookup_table[dev_data->devid];
1657
1658         /* decrease reference counters */
1659         dev_data->domain->dev_iommu[iommu->index] -= 1;
1660         dev_data->domain->dev_cnt                 -= 1;
1661
1662         /* Update data structures */
1663         dev_data->domain = NULL;
1664         list_del(&dev_data->list);
1665         clear_dte_entry(dev_data->devid);
1666
1667         /* Flush the DTE entry */
1668         device_flush_dte(dev_data);
1669 }
1670
1671 /*
1672  * If a device is not yet associated with a domain, this function does
1673  * assigns it visible for the hardware
1674  */
1675 static int __attach_device(struct iommu_dev_data *dev_data,
1676                            struct protection_domain *domain)
1677 {
1678         int ret;
1679
1680         /* lock domain */
1681         spin_lock(&domain->lock);
1682
1683         if (dev_data->alias_data != NULL) {
1684                 struct iommu_dev_data *alias_data = dev_data->alias_data;
1685
1686                 /* Some sanity checks */
1687                 ret = -EBUSY;
1688                 if (alias_data->domain != NULL &&
1689                                 alias_data->domain != domain)
1690                         goto out_unlock;
1691
1692                 if (dev_data->domain != NULL &&
1693                                 dev_data->domain != domain)
1694                         goto out_unlock;
1695
1696                 /* Do real assignment */
1697                 if (alias_data->domain == NULL)
1698                         do_attach(alias_data, domain);
1699
1700                 atomic_inc(&alias_data->bind);
1701         }
1702
1703         if (dev_data->domain == NULL)
1704                 do_attach(dev_data, domain);
1705
1706         atomic_inc(&dev_data->bind);
1707
1708         ret = 0;
1709
1710 out_unlock:
1711
1712         /* ready */
1713         spin_unlock(&domain->lock);
1714
1715         return ret;
1716 }
1717
1718 /*
1719  * If a device is not yet associated with a domain, this function does
1720  * assigns it visible for the hardware
1721  */
1722 static int attach_device(struct device *dev,
1723                          struct protection_domain *domain)
1724 {
1725         struct pci_dev *pdev = to_pci_dev(dev);
1726         struct iommu_dev_data *dev_data;
1727         unsigned long flags;
1728         int ret;
1729
1730         dev_data = get_dev_data(dev);
1731
1732         if (amd_iommu_iotlb_sup && pci_enable_ats(pdev, PAGE_SHIFT) == 0) {
1733                 dev_data->ats.enabled = true;
1734                 dev_data->ats.qdep    = pci_ats_queue_depth(pdev);
1735         }
1736
1737         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1738         ret = __attach_device(dev_data, domain);
1739         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1740
1741         /*
1742          * We might boot into a crash-kernel here. The crashed kernel
1743          * left the caches in the IOMMU dirty. So we have to flush
1744          * here to evict all dirty stuff.
1745          */
1746         domain_flush_tlb_pde(domain);
1747
1748         return ret;
1749 }
1750
1751 /*
1752  * Removes a device from a protection domain (unlocked)
1753  */
1754 static void __detach_device(struct iommu_dev_data *dev_data)
1755 {
1756         struct protection_domain *domain;
1757         unsigned long flags;
1758
1759         BUG_ON(!dev_data->domain);
1760
1761         domain = dev_data->domain;
1762
1763         spin_lock_irqsave(&domain->lock, flags);
1764
1765         if (dev_data->alias_data != NULL) {
1766                 struct iommu_dev_data *alias_data = dev_data->alias_data;
1767
1768                 if (atomic_dec_and_test(&alias_data->bind))
1769                         do_detach(alias_data);
1770         }
1771
1772         if (atomic_dec_and_test(&dev_data->bind))
1773                 do_detach(dev_data);
1774
1775         spin_unlock_irqrestore(&domain->lock, flags);
1776
1777         /*
1778          * If we run in passthrough mode the device must be assigned to the
1779          * passthrough domain if it is detached from any other domain.
1780          * Make sure we can deassign from the pt_domain itself.
1781          */
1782         if (iommu_pass_through &&
1783             (dev_data->domain == NULL && domain != pt_domain))
1784                 __attach_device(dev_data, pt_domain);
1785 }
1786
1787 /*
1788  * Removes a device from a protection domain (with devtable_lock held)
1789  */
1790 static void detach_device(struct device *dev)
1791 {
1792         struct iommu_dev_data *dev_data;
1793         unsigned long flags;
1794
1795         dev_data = get_dev_data(dev);
1796
1797         /* lock device table */
1798         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
1799         __detach_device(dev_data);
1800         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1801
1802         if (dev_data->ats.enabled) {
1803                 pci_disable_ats(to_pci_dev(dev));
1804                 dev_data->ats.enabled = false;
1805         }
1806 }
1807
1808 /*
1809  * Find out the protection domain structure for a given PCI device. This
1810  * will give us the pointer to the page table root for example.
1811  */
1812 static struct protection_domain *domain_for_device(struct device *dev)
1813 {
1814         struct iommu_dev_data *dev_data;
1815         struct protection_domain *dom = NULL;
1816         unsigned long flags;
1817
1818         dev_data   = get_dev_data(dev);
1819
1820         if (dev_data->domain)
1821                 return dev_data->domain;
1822
1823         if (dev_data->alias_data != NULL) {
1824                 struct iommu_dev_data *alias_data = dev_data->alias_data;
1825
1826                 read_lock_irqsave(&amd_iommu_devtable_lock, flags);
1827                 if (alias_data->domain != NULL) {
1828                         __attach_device(dev_data, alias_data->domain);
1829                         dom = alias_data->domain;
1830                 }
1831                 read_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
1832         }
1833
1834         return dom;
1835 }
1836
1837 static int device_change_notifier(struct notifier_block *nb,
1838                                   unsigned long action, void *data)
1839 {
1840         struct device *dev = data;
1841         u16 devid;
1842         struct protection_domain *domain;
1843         struct dma_ops_domain *dma_domain;
1844         struct amd_iommu *iommu;
1845         unsigned long flags;
1846
1847         if (!check_device(dev))
1848                 return 0;
1849
1850         devid  = get_device_id(dev);
1851         iommu  = amd_iommu_rlookup_table[devid];
1852
1853         switch (action) {
1854         case BUS_NOTIFY_UNBOUND_DRIVER:
1855
1856                 domain = domain_for_device(dev);
1857
1858                 if (!domain)
1859                         goto out;
1860                 if (iommu_pass_through)
1861                         break;
1862                 detach_device(dev);
1863                 break;
1864         case BUS_NOTIFY_ADD_DEVICE:
1865
1866                 iommu_init_device(dev);
1867
1868                 if (iommu_pass_through) {
1869                         attach_device(dev, pt_domain);
1870                         break;
1871                 }
1872
1873                 domain = domain_for_device(dev);
1874
1875                 /* allocate a protection domain if a device is added */
1876                 dma_domain = find_protection_domain(devid);
1877                 if (dma_domain)
1878                         goto out;
1879                 dma_domain = dma_ops_domain_alloc();
1880                 if (!dma_domain)
1881                         goto out;
1882                 dma_domain->target_dev = devid;
1883
1884                 spin_lock_irqsave(&iommu_pd_list_lock, flags);
1885                 list_add_tail(&dma_domain->list, &iommu_pd_list);
1886                 spin_unlock_irqrestore(&iommu_pd_list_lock, flags);
1887
1888                 dev->archdata.dma_ops = &amd_iommu_dma_ops;
1889
1890                 break;
1891         case BUS_NOTIFY_DEL_DEVICE:
1892
1893                 iommu_uninit_device(dev);
1894
1895         default:
1896                 goto out;
1897         }
1898
1899         iommu_completion_wait(iommu);
1900
1901 out:
1902         return 0;
1903 }
1904
1905 static struct notifier_block device_nb = {
1906         .notifier_call = device_change_notifier,
1907 };
1908
1909 void amd_iommu_init_notifier(void)
1910 {
1911         bus_register_notifier(&pci_bus_type, &device_nb);
1912 }
1913
1914 /*****************************************************************************
1915  *
1916  * The next functions belong to the dma_ops mapping/unmapping code.
1917  *
1918  *****************************************************************************/
1919
1920 /*
1921  * In the dma_ops path we only have the struct device. This function
1922  * finds the corresponding IOMMU, the protection domain and the
1923  * requestor id for a given device.
1924  * If the device is not yet associated with a domain this is also done
1925  * in this function.
1926  */
1927 static struct protection_domain *get_domain(struct device *dev)
1928 {
1929         struct protection_domain *domain;
1930         struct dma_ops_domain *dma_dom;
1931         u16 devid = get_device_id(dev);
1932
1933         if (!check_device(dev))
1934                 return ERR_PTR(-EINVAL);
1935
1936         domain = domain_for_device(dev);
1937         if (domain != NULL && !dma_ops_domain(domain))
1938                 return ERR_PTR(-EBUSY);
1939
1940         if (domain != NULL)
1941                 return domain;
1942
1943         /* Device not bount yet - bind it */
1944         dma_dom = find_protection_domain(devid);
1945         if (!dma_dom)
1946                 dma_dom = amd_iommu_rlookup_table[devid]->default_dom;
1947         attach_device(dev, &dma_dom->domain);
1948         DUMP_printk("Using protection domain %d for device %s\n",
1949                     dma_dom->domain.id, dev_name(dev));
1950
1951         return &dma_dom->domain;
1952 }
1953
1954 static void update_device_table(struct protection_domain *domain)
1955 {
1956         struct iommu_dev_data *dev_data;
1957
1958         list_for_each_entry(dev_data, &domain->dev_list, list)
1959                 set_dte_entry(dev_data->devid, domain, dev_data->ats.enabled);
1960 }
1961
1962 static void update_domain(struct protection_domain *domain)
1963 {
1964         if (!domain->updated)
1965                 return;
1966
1967         update_device_table(domain);
1968
1969         domain_flush_devices(domain);
1970         domain_flush_tlb_pde(domain);
1971
1972         domain->updated = false;
1973 }
1974
1975 /*
1976  * This function fetches the PTE for a given address in the aperture
1977  */
1978 static u64* dma_ops_get_pte(struct dma_ops_domain *dom,
1979                             unsigned long address)
1980 {
1981         struct aperture_range *aperture;
1982         u64 *pte, *pte_page;
1983
1984         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
1985         if (!aperture)
1986                 return NULL;
1987
1988         pte = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
1989         if (!pte) {
1990                 pte = alloc_pte(&dom->domain, address, PAGE_SIZE, &pte_page,
1991                                 GFP_ATOMIC);
1992                 aperture->pte_pages[APERTURE_PAGE_INDEX(address)] = pte_page;
1993         } else
1994                 pte += PM_LEVEL_INDEX(0, address);
1995
1996         update_domain(&dom->domain);
1997
1998         return pte;
1999 }
2000
2001 /*
2002  * This is the generic map function. It maps one 4kb page at paddr to
2003  * the given address in the DMA address space for the domain.
2004  */
2005 static dma_addr_t dma_ops_domain_map(struct dma_ops_domain *dom,
2006                                      unsigned long address,
2007                                      phys_addr_t paddr,
2008                                      int direction)
2009 {
2010         u64 *pte, __pte;
2011
2012         WARN_ON(address > dom->aperture_size);
2013
2014         paddr &= PAGE_MASK;
2015
2016         pte  = dma_ops_get_pte(dom, address);
2017         if (!pte)
2018                 return DMA_ERROR_CODE;
2019
2020         __pte = paddr | IOMMU_PTE_P | IOMMU_PTE_FC;
2021
2022         if (direction == DMA_TO_DEVICE)
2023                 __pte |= IOMMU_PTE_IR;
2024         else if (direction == DMA_FROM_DEVICE)
2025                 __pte |= IOMMU_PTE_IW;
2026         else if (direction == DMA_BIDIRECTIONAL)
2027                 __pte |= IOMMU_PTE_IR | IOMMU_PTE_IW;
2028
2029         WARN_ON(*pte);
2030
2031         *pte = __pte;
2032
2033         return (dma_addr_t)address;
2034 }
2035
2036 /*
2037  * The generic unmapping function for on page in the DMA address space.
2038  */
2039 static void dma_ops_domain_unmap(struct dma_ops_domain *dom,
2040                                  unsigned long address)
2041 {
2042         struct aperture_range *aperture;
2043         u64 *pte;
2044
2045         if (address >= dom->aperture_size)
2046                 return;
2047
2048         aperture = dom->aperture[APERTURE_RANGE_INDEX(address)];
2049         if (!aperture)
2050                 return;
2051
2052         pte  = aperture->pte_pages[APERTURE_PAGE_INDEX(address)];
2053         if (!pte)
2054                 return;
2055
2056         pte += PM_LEVEL_INDEX(0, address);
2057
2058         WARN_ON(!*pte);
2059
2060         *pte = 0ULL;
2061 }
2062
2063 /*
2064  * This function contains common code for mapping of a physically
2065  * contiguous memory region into DMA address space. It is used by all
2066  * mapping functions provided with this IOMMU driver.
2067  * Must be called with the domain lock held.
2068  */
2069 static dma_addr_t __map_single(struct device *dev,
2070                                struct dma_ops_domain *dma_dom,
2071                                phys_addr_t paddr,
2072                                size_t size,
2073                                int dir,
2074                                bool align,
2075                                u64 dma_mask)
2076 {
2077         dma_addr_t offset = paddr & ~PAGE_MASK;
2078         dma_addr_t address, start, ret;
2079         unsigned int pages;
2080         unsigned long align_mask = 0;
2081         int i;
2082
2083         pages = iommu_num_pages(paddr, size, PAGE_SIZE);
2084         paddr &= PAGE_MASK;
2085
2086         INC_STATS_COUNTER(total_map_requests);
2087
2088         if (pages > 1)
2089                 INC_STATS_COUNTER(cross_page);
2090
2091         if (align)
2092                 align_mask = (1UL << get_order(size)) - 1;
2093
2094 retry:
2095         address = dma_ops_alloc_addresses(dev, dma_dom, pages, align_mask,
2096                                           dma_mask);
2097         if (unlikely(address == DMA_ERROR_CODE)) {
2098                 /*
2099                  * setting next_address here will let the address
2100                  * allocator only scan the new allocated range in the
2101                  * first run. This is a small optimization.
2102                  */
2103                 dma_dom->next_address = dma_dom->aperture_size;
2104
2105                 if (alloc_new_range(dma_dom, false, GFP_ATOMIC))
2106                         goto out;
2107
2108                 /*
2109                  * aperture was successfully enlarged by 128 MB, try
2110                  * allocation again
2111                  */
2112                 goto retry;
2113         }
2114
2115         start = address;
2116         for (i = 0; i < pages; ++i) {
2117                 ret = dma_ops_domain_map(dma_dom, start, paddr, dir);
2118                 if (ret == DMA_ERROR_CODE)
2119                         goto out_unmap;
2120
2121                 paddr += PAGE_SIZE;
2122                 start += PAGE_SIZE;
2123         }
2124         address += offset;
2125
2126         ADD_STATS_COUNTER(alloced_io_mem, size);
2127
2128         if (unlikely(dma_dom->need_flush && !amd_iommu_unmap_flush)) {
2129                 domain_flush_tlb(&dma_dom->domain);
2130                 dma_dom->need_flush = false;
2131         } else if (unlikely(amd_iommu_np_cache))
2132                 domain_flush_pages(&dma_dom->domain, address, size);
2133
2134 out:
2135         return address;
2136
2137 out_unmap:
2138
2139         for (--i; i >= 0; --i) {
2140                 start -= PAGE_SIZE;
2141                 dma_ops_domain_unmap(dma_dom, start);
2142         }
2143
2144         dma_ops_free_addresses(dma_dom, address, pages);
2145
2146         return DMA_ERROR_CODE;
2147 }
2148
2149 /*
2150  * Does the reverse of the __map_single function. Must be called with
2151  * the domain lock held too
2152  */
2153 static void __unmap_single(struct dma_ops_domain *dma_dom,
2154                            dma_addr_t dma_addr,
2155                            size_t size,
2156                            int dir)
2157 {
2158         dma_addr_t flush_addr;
2159         dma_addr_t i, start;
2160         unsigned int pages;
2161
2162         if ((dma_addr == DMA_ERROR_CODE) ||
2163             (dma_addr + size > dma_dom->aperture_size))
2164                 return;
2165
2166         flush_addr = dma_addr;
2167         pages = iommu_num_pages(dma_addr, size, PAGE_SIZE);
2168         dma_addr &= PAGE_MASK;
2169         start = dma_addr;
2170
2171         for (i = 0; i < pages; ++i) {
2172                 dma_ops_domain_unmap(dma_dom, start);
2173                 start += PAGE_SIZE;
2174         }
2175
2176         SUB_STATS_COUNTER(alloced_io_mem, size);
2177
2178         dma_ops_free_addresses(dma_dom, dma_addr, pages);
2179
2180         if (amd_iommu_unmap_flush || dma_dom->need_flush) {
2181                 domain_flush_pages(&dma_dom->domain, flush_addr, size);
2182                 dma_dom->need_flush = false;
2183         }
2184 }
2185
2186 /*
2187  * The exported map_single function for dma_ops.
2188  */
2189 static dma_addr_t map_page(struct device *dev, struct page *page,
2190                            unsigned long offset, size_t size,
2191                            enum dma_data_direction dir,
2192                            struct dma_attrs *attrs)
2193 {
2194         unsigned long flags;
2195         struct protection_domain *domain;
2196         dma_addr_t addr;
2197         u64 dma_mask;
2198         phys_addr_t paddr = page_to_phys(page) + offset;
2199
2200         INC_STATS_COUNTER(cnt_map_single);
2201
2202         domain = get_domain(dev);
2203         if (PTR_ERR(domain) == -EINVAL)
2204                 return (dma_addr_t)paddr;
2205         else if (IS_ERR(domain))
2206                 return DMA_ERROR_CODE;
2207
2208         dma_mask = *dev->dma_mask;
2209
2210         spin_lock_irqsave(&domain->lock, flags);
2211
2212         addr = __map_single(dev, domain->priv, paddr, size, dir, false,
2213                             dma_mask);
2214         if (addr == DMA_ERROR_CODE)
2215                 goto out;
2216
2217         domain_flush_complete(domain);
2218
2219 out:
2220         spin_unlock_irqrestore(&domain->lock, flags);
2221
2222         return addr;
2223 }
2224
2225 /*
2226  * The exported unmap_single function for dma_ops.
2227  */
2228 static void unmap_page(struct device *dev, dma_addr_t dma_addr, size_t size,
2229                        enum dma_data_direction dir, struct dma_attrs *attrs)
2230 {
2231         unsigned long flags;
2232         struct protection_domain *domain;
2233
2234         INC_STATS_COUNTER(cnt_unmap_single);
2235
2236         domain = get_domain(dev);
2237         if (IS_ERR(domain))
2238                 return;
2239
2240         spin_lock_irqsave(&domain->lock, flags);
2241
2242         __unmap_single(domain->priv, dma_addr, size, dir);
2243
2244         domain_flush_complete(domain);
2245
2246         spin_unlock_irqrestore(&domain->lock, flags);
2247 }
2248
2249 /*
2250  * This is a special map_sg function which is used if we should map a
2251  * device which is not handled by an AMD IOMMU in the system.
2252  */
2253 static int map_sg_no_iommu(struct device *dev, struct scatterlist *sglist,
2254                            int nelems, int dir)
2255 {
2256         struct scatterlist *s;
2257         int i;
2258
2259         for_each_sg(sglist, s, nelems, i) {
2260                 s->dma_address = (dma_addr_t)sg_phys(s);
2261                 s->dma_length  = s->length;
2262         }
2263
2264         return nelems;
2265 }
2266
2267 /*
2268  * The exported map_sg function for dma_ops (handles scatter-gather
2269  * lists).
2270  */
2271 static int map_sg(struct device *dev, struct scatterlist *sglist,
2272                   int nelems, enum dma_data_direction dir,
2273                   struct dma_attrs *attrs)
2274 {
2275         unsigned long flags;
2276         struct protection_domain *domain;
2277         int i;
2278         struct scatterlist *s;
2279         phys_addr_t paddr;
2280         int mapped_elems = 0;
2281         u64 dma_mask;
2282
2283         INC_STATS_COUNTER(cnt_map_sg);
2284
2285         domain = get_domain(dev);
2286         if (PTR_ERR(domain) == -EINVAL)
2287                 return map_sg_no_iommu(dev, sglist, nelems, dir);
2288         else if (IS_ERR(domain))
2289                 return 0;
2290
2291         dma_mask = *dev->dma_mask;
2292
2293         spin_lock_irqsave(&domain->lock, flags);
2294
2295         for_each_sg(sglist, s, nelems, i) {
2296                 paddr = sg_phys(s);
2297
2298                 s->dma_address = __map_single(dev, domain->priv,
2299                                               paddr, s->length, dir, false,
2300                                               dma_mask);
2301
2302                 if (s->dma_address) {
2303                         s->dma_length = s->length;
2304                         mapped_elems++;
2305                 } else
2306                         goto unmap;
2307         }
2308
2309         domain_flush_complete(domain);
2310
2311 out:
2312         spin_unlock_irqrestore(&domain->lock, flags);
2313
2314         return mapped_elems;
2315 unmap:
2316         for_each_sg(sglist, s, mapped_elems, i) {
2317                 if (s->dma_address)
2318                         __unmap_single(domain->priv, s->dma_address,
2319                                        s->dma_length, dir);
2320                 s->dma_address = s->dma_length = 0;
2321         }
2322
2323         mapped_elems = 0;
2324
2325         goto out;
2326 }
2327
2328 /*
2329  * The exported map_sg function for dma_ops (handles scatter-gather
2330  * lists).
2331  */
2332 static void unmap_sg(struct device *dev, struct scatterlist *sglist,
2333                      int nelems, enum dma_data_direction dir,
2334                      struct dma_attrs *attrs)
2335 {
2336         unsigned long flags;
2337         struct protection_domain *domain;
2338         struct scatterlist *s;
2339         int i;
2340
2341         INC_STATS_COUNTER(cnt_unmap_sg);
2342
2343         domain = get_domain(dev);
2344         if (IS_ERR(domain))
2345                 return;
2346
2347         spin_lock_irqsave(&domain->lock, flags);
2348
2349         for_each_sg(sglist, s, nelems, i) {
2350                 __unmap_single(domain->priv, s->dma_address,
2351                                s->dma_length, dir);
2352                 s->dma_address = s->dma_length = 0;
2353         }
2354
2355         domain_flush_complete(domain);
2356
2357         spin_unlock_irqrestore(&domain->lock, flags);
2358 }
2359
2360 /*
2361  * The exported alloc_coherent function for dma_ops.
2362  */
2363 static void *alloc_coherent(struct device *dev, size_t size,
2364                             dma_addr_t *dma_addr, gfp_t flag)
2365 {
2366         unsigned long flags;
2367         void *virt_addr;
2368         struct protection_domain *domain;
2369         phys_addr_t paddr;
2370         u64 dma_mask = dev->coherent_dma_mask;
2371
2372         INC_STATS_COUNTER(cnt_alloc_coherent);
2373
2374         domain = get_domain(dev);
2375         if (PTR_ERR(domain) == -EINVAL) {
2376                 virt_addr = (void *)__get_free_pages(flag, get_order(size));
2377                 *dma_addr = __pa(virt_addr);
2378                 return virt_addr;
2379         } else if (IS_ERR(domain))
2380                 return NULL;
2381
2382         dma_mask  = dev->coherent_dma_mask;
2383         flag     &= ~(__GFP_DMA | __GFP_HIGHMEM | __GFP_DMA32);
2384         flag     |= __GFP_ZERO;
2385
2386         virt_addr = (void *)__get_free_pages(flag, get_order(size));
2387         if (!virt_addr)
2388                 return NULL;
2389
2390         paddr = virt_to_phys(virt_addr);
2391
2392         if (!dma_mask)
2393                 dma_mask = *dev->dma_mask;
2394
2395         spin_lock_irqsave(&domain->lock, flags);
2396
2397         *dma_addr = __map_single(dev, domain->priv, paddr,
2398                                  size, DMA_BIDIRECTIONAL, true, dma_mask);
2399
2400         if (*dma_addr == DMA_ERROR_CODE) {
2401                 spin_unlock_irqrestore(&domain->lock, flags);
2402                 goto out_free;
2403         }
2404
2405         domain_flush_complete(domain);
2406
2407         spin_unlock_irqrestore(&domain->lock, flags);
2408
2409         return virt_addr;
2410
2411 out_free:
2412
2413         free_pages((unsigned long)virt_addr, get_order(size));
2414
2415         return NULL;
2416 }
2417
2418 /*
2419  * The exported free_coherent function for dma_ops.
2420  */
2421 static void free_coherent(struct device *dev, size_t size,
2422                           void *virt_addr, dma_addr_t dma_addr)
2423 {
2424         unsigned long flags;
2425         struct protection_domain *domain;
2426
2427         INC_STATS_COUNTER(cnt_free_coherent);
2428
2429         domain = get_domain(dev);
2430         if (IS_ERR(domain))
2431                 goto free_mem;
2432
2433         spin_lock_irqsave(&domain->lock, flags);
2434
2435         __unmap_single(domain->priv, dma_addr, size, DMA_BIDIRECTIONAL);
2436
2437         domain_flush_complete(domain);
2438
2439         spin_unlock_irqrestore(&domain->lock, flags);
2440
2441 free_mem:
2442         free_pages((unsigned long)virt_addr, get_order(size));
2443 }
2444
2445 /*
2446  * This function is called by the DMA layer to find out if we can handle a
2447  * particular device. It is part of the dma_ops.
2448  */
2449 static int amd_iommu_dma_supported(struct device *dev, u64 mask)
2450 {
2451         return check_device(dev);
2452 }
2453
2454 /*
2455  * The function for pre-allocating protection domains.
2456  *
2457  * If the driver core informs the DMA layer if a driver grabs a device
2458  * we don't need to preallocate the protection domains anymore.
2459  * For now we have to.
2460  */
2461 static void __init prealloc_protection_domains(void)
2462 {
2463         struct pci_dev *dev = NULL;
2464         struct dma_ops_domain *dma_dom;
2465         u16 devid;
2466
2467         for_each_pci_dev(dev) {
2468
2469                 /* Do we handle this device? */
2470                 if (!check_device(&dev->dev))
2471                         continue;
2472
2473                 /* Is there already any domain for it? */
2474                 if (domain_for_device(&dev->dev))
2475                         continue;
2476
2477                 devid = get_device_id(&dev->dev);
2478
2479                 dma_dom = dma_ops_domain_alloc();
2480                 if (!dma_dom)
2481                         continue;
2482                 init_unity_mappings_for_device(dma_dom, devid);
2483                 dma_dom->target_dev = devid;
2484
2485                 attach_device(&dev->dev, &dma_dom->domain);
2486
2487                 list_add_tail(&dma_dom->list, &iommu_pd_list);
2488         }
2489 }
2490
2491 static struct dma_map_ops amd_iommu_dma_ops = {
2492         .alloc_coherent = alloc_coherent,
2493         .free_coherent = free_coherent,
2494         .map_page = map_page,
2495         .unmap_page = unmap_page,
2496         .map_sg = map_sg,
2497         .unmap_sg = unmap_sg,
2498         .dma_supported = amd_iommu_dma_supported,
2499 };
2500
2501 static unsigned device_dma_ops_init(void)
2502 {
2503         struct pci_dev *pdev = NULL;
2504         unsigned unhandled = 0;
2505
2506         for_each_pci_dev(pdev) {
2507                 if (!check_device(&pdev->dev)) {
2508
2509                         iommu_ignore_device(&pdev->dev);
2510
2511                         unhandled += 1;
2512                         continue;
2513                 }
2514
2515                 pdev->dev.archdata.dma_ops = &amd_iommu_dma_ops;
2516         }
2517
2518         return unhandled;
2519 }
2520
2521 /*
2522  * The function which clues the AMD IOMMU driver into dma_ops.
2523  */
2524
2525 void __init amd_iommu_init_api(void)
2526 {
2527         bus_set_iommu(&pci_bus_type, &amd_iommu_ops);
2528 }
2529
2530 int __init amd_iommu_init_dma_ops(void)
2531 {
2532         struct amd_iommu *iommu;
2533         int ret, unhandled;
2534
2535         /*
2536          * first allocate a default protection domain for every IOMMU we
2537          * found in the system. Devices not assigned to any other
2538          * protection domain will be assigned to the default one.
2539          */
2540         for_each_iommu(iommu) {
2541                 iommu->default_dom = dma_ops_domain_alloc();
2542                 if (iommu->default_dom == NULL)
2543                         return -ENOMEM;
2544                 iommu->default_dom->domain.flags |= PD_DEFAULT_MASK;
2545                 ret = iommu_init_unity_mappings(iommu);
2546                 if (ret)
2547                         goto free_domains;
2548         }
2549
2550         /*
2551          * Pre-allocate the protection domains for each device.
2552          */
2553         prealloc_protection_domains();
2554
2555         iommu_detected = 1;
2556         swiotlb = 0;
2557
2558         /* Make the driver finally visible to the drivers */
2559         unhandled = device_dma_ops_init();
2560         if (unhandled && max_pfn > MAX_DMA32_PFN) {
2561                 /* There are unhandled devices - initialize swiotlb for them */
2562                 swiotlb = 1;
2563         }
2564
2565         amd_iommu_stats_init();
2566
2567         return 0;
2568
2569 free_domains:
2570
2571         for_each_iommu(iommu) {
2572                 if (iommu->default_dom)
2573                         dma_ops_domain_free(iommu->default_dom);
2574         }
2575
2576         return ret;
2577 }
2578
2579 /*****************************************************************************
2580  *
2581  * The following functions belong to the exported interface of AMD IOMMU
2582  *
2583  * This interface allows access to lower level functions of the IOMMU
2584  * like protection domain handling and assignement of devices to domains
2585  * which is not possible with the dma_ops interface.
2586  *
2587  *****************************************************************************/
2588
2589 static void cleanup_domain(struct protection_domain *domain)
2590 {
2591         struct iommu_dev_data *dev_data, *next;
2592         unsigned long flags;
2593
2594         write_lock_irqsave(&amd_iommu_devtable_lock, flags);
2595
2596         list_for_each_entry_safe(dev_data, next, &domain->dev_list, list) {
2597                 __detach_device(dev_data);
2598                 atomic_set(&dev_data->bind, 0);
2599         }
2600
2601         write_unlock_irqrestore(&amd_iommu_devtable_lock, flags);
2602 }
2603
2604 static void protection_domain_free(struct protection_domain *domain)
2605 {
2606         if (!domain)
2607                 return;
2608
2609         del_domain_from_list(domain);
2610
2611         if (domain->id)
2612                 domain_id_free(domain->id);
2613
2614         kfree(domain);
2615 }
2616
2617 static struct protection_domain *protection_domain_alloc(void)
2618 {
2619         struct protection_domain *domain;
2620
2621         domain = kzalloc(sizeof(*domain), GFP_KERNEL);
2622         if (!domain)
2623                 return NULL;
2624
2625         spin_lock_init(&domain->lock);
2626         mutex_init(&domain->api_lock);
2627         domain->id = domain_id_alloc();
2628         if (!domain->id)
2629                 goto out_err;
2630         INIT_LIST_HEAD(&domain->dev_list);
2631
2632         add_domain_to_list(domain);
2633
2634         return domain;
2635
2636 out_err:
2637         kfree(domain);
2638
2639         return NULL;
2640 }
2641
2642 static int amd_iommu_domain_init(struct iommu_domain *dom)
2643 {
2644         struct protection_domain *domain;
2645
2646         domain = protection_domain_alloc();
2647         if (!domain)
2648                 goto out_free;
2649
2650         domain->mode    = PAGE_MODE_3_LEVEL;
2651         domain->pt_root = (void *)get_zeroed_page(GFP_KERNEL);
2652         if (!domain->pt_root)
2653                 goto out_free;
2654
2655         dom->priv = domain;
2656
2657         return 0;
2658
2659 out_free:
2660         protection_domain_free(domain);
2661
2662         return -ENOMEM;
2663 }
2664
2665 static void amd_iommu_domain_destroy(struct iommu_domain *dom)
2666 {
2667         struct protection_domain *domain = dom->priv;
2668
2669         if (!domain)
2670                 return;
2671
2672         if (domain->dev_cnt > 0)
2673                 cleanup_domain(domain);
2674
2675         BUG_ON(domain->dev_cnt != 0);
2676
2677         free_pagetable(domain);
2678
2679         protection_domain_free(domain);
2680
2681         dom->priv = NULL;
2682 }
2683
2684 static void amd_iommu_detach_device(struct iommu_domain *dom,
2685                                     struct device *dev)
2686 {
2687         struct iommu_dev_data *dev_data = dev->archdata.iommu;
2688         struct amd_iommu *iommu;
2689         u16 devid;
2690
2691         if (!check_device(dev))
2692                 return;
2693
2694         devid = get_device_id(dev);
2695
2696         if (dev_data->domain != NULL)
2697                 detach_device(dev);
2698
2699         iommu = amd_iommu_rlookup_table[devid];
2700         if (!iommu)
2701                 return;
2702
2703         iommu_completion_wait(iommu);
2704 }
2705
2706 static int amd_iommu_attach_device(struct iommu_domain *dom,
2707                                    struct device *dev)
2708 {
2709         struct protection_domain *domain = dom->priv;
2710         struct iommu_dev_data *dev_data;
2711         struct amd_iommu *iommu;
2712         int ret;
2713
2714         if (!check_device(dev))
2715                 return -EINVAL;
2716
2717         dev_data = dev->archdata.iommu;
2718
2719         iommu = amd_iommu_rlookup_table[dev_data->devid];
2720         if (!iommu)
2721                 return -EINVAL;
2722
2723         if (dev_data->domain)
2724                 detach_device(dev);
2725
2726         ret = attach_device(dev, domain);
2727
2728         iommu_completion_wait(iommu);
2729
2730         return ret;
2731 }
2732
2733 static int amd_iommu_map(struct iommu_domain *dom, unsigned long iova,
2734                          phys_addr_t paddr, int gfp_order, int iommu_prot)
2735 {
2736         unsigned long page_size = 0x1000UL << gfp_order;
2737         struct protection_domain *domain = dom->priv;
2738         int prot = 0;
2739         int ret;
2740
2741         if (iommu_prot & IOMMU_READ)
2742                 prot |= IOMMU_PROT_IR;
2743         if (iommu_prot & IOMMU_WRITE)
2744                 prot |= IOMMU_PROT_IW;
2745
2746         mutex_lock(&domain->api_lock);
2747         ret = iommu_map_page(domain, iova, paddr, prot, page_size);
2748         mutex_unlock(&domain->api_lock);
2749
2750         return ret;
2751 }
2752
2753 static int amd_iommu_unmap(struct iommu_domain *dom, unsigned long iova,
2754                            int gfp_order)
2755 {
2756         struct protection_domain *domain = dom->priv;
2757         unsigned long page_size, unmap_size;
2758
2759         page_size  = 0x1000UL << gfp_order;
2760
2761         mutex_lock(&domain->api_lock);
2762         unmap_size = iommu_unmap_page(domain, iova, page_size);
2763         mutex_unlock(&domain->api_lock);
2764
2765         domain_flush_tlb_pde(domain);
2766
2767         return get_order(unmap_size);
2768 }
2769
2770 static phys_addr_t amd_iommu_iova_to_phys(struct iommu_domain *dom,
2771                                           unsigned long iova)
2772 {
2773         struct protection_domain *domain = dom->priv;
2774         unsigned long offset_mask;
2775         phys_addr_t paddr;
2776         u64 *pte, __pte;
2777
2778         pte = fetch_pte(domain, iova);
2779
2780         if (!pte || !IOMMU_PTE_PRESENT(*pte))
2781                 return 0;
2782
2783         if (PM_PTE_LEVEL(*pte) == 0)
2784                 offset_mask = PAGE_SIZE - 1;
2785         else
2786                 offset_mask = PTE_PAGE_SIZE(*pte) - 1;
2787
2788         __pte = *pte & PM_ADDR_MASK;
2789         paddr = (__pte & ~offset_mask) | (iova & offset_mask);
2790
2791         return paddr;
2792 }
2793
2794 static int amd_iommu_domain_has_cap(struct iommu_domain *domain,
2795                                     unsigned long cap)
2796 {
2797         switch (cap) {
2798         case IOMMU_CAP_CACHE_COHERENCY:
2799                 return 1;
2800         }
2801
2802         return 0;
2803 }
2804
2805 static struct iommu_ops amd_iommu_ops = {
2806         .domain_init = amd_iommu_domain_init,
2807         .domain_destroy = amd_iommu_domain_destroy,
2808         .attach_dev = amd_iommu_attach_device,
2809         .detach_dev = amd_iommu_detach_device,
2810         .map = amd_iommu_map,
2811         .unmap = amd_iommu_unmap,
2812         .iova_to_phys = amd_iommu_iova_to_phys,
2813         .domain_has_cap = amd_iommu_domain_has_cap,
2814 };
2815
2816 /*****************************************************************************
2817  *
2818  * The next functions do a basic initialization of IOMMU for pass through
2819  * mode
2820  *
2821  * In passthrough mode the IOMMU is initialized and enabled but not used for
2822  * DMA-API translation.
2823  *
2824  *****************************************************************************/
2825
2826 int __init amd_iommu_init_passthrough(void)
2827 {
2828         struct amd_iommu *iommu;
2829         struct pci_dev *dev = NULL;
2830         u16 devid;
2831
2832         /* allocate passthrough domain */
2833         pt_domain = protection_domain_alloc();
2834         if (!pt_domain)
2835                 return -ENOMEM;
2836
2837         pt_domain->mode |= PAGE_MODE_NONE;
2838
2839         for_each_pci_dev(dev) {
2840                 if (!check_device(&dev->dev))
2841                         continue;
2842
2843                 devid = get_device_id(&dev->dev);
2844
2845                 iommu = amd_iommu_rlookup_table[devid];
2846                 if (!iommu)
2847                         continue;
2848
2849                 attach_device(&dev->dev, pt_domain);
2850         }
2851
2852         pr_info("AMD-Vi: Initialized for Passthrough Mode\n");
2853
2854         return 0;
2855 }