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