x86: enable_update_mptable should be a macro
[safe/jmp/linux-2.6] / drivers / pci / intel-iommu.c
1 /*
2  * Copyright (c) 2006, Intel Corporation.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms and conditions of the GNU General Public License,
6  * version 2, as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11  * more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
15  * Place - Suite 330, Boston, MA 02111-1307 USA.
16  *
17  * Copyright (C) 2006-2008 Intel Corporation
18  * Author: Ashok Raj <ashok.raj@intel.com>
19  * Author: Shaohua Li <shaohua.li@intel.com>
20  * Author: Anil S Keshavamurthy <anil.s.keshavamurthy@intel.com>
21  * Author: Fenghua Yu <fenghua.yu@intel.com>
22  */
23
24 #include <linux/init.h>
25 #include <linux/bitmap.h>
26 #include <linux/debugfs.h>
27 #include <linux/slab.h>
28 #include <linux/irq.h>
29 #include <linux/interrupt.h>
30 #include <linux/spinlock.h>
31 #include <linux/pci.h>
32 #include <linux/dmar.h>
33 #include <linux/dma-mapping.h>
34 #include <linux/mempool.h>
35 #include <linux/timer.h>
36 #include <linux/iova.h>
37 #include <linux/iommu.h>
38 #include <linux/intel-iommu.h>
39 #include <linux/sysdev.h>
40 #include <asm/cacheflush.h>
41 #include <asm/iommu.h>
42 #include "pci.h"
43
44 #define ROOT_SIZE               VTD_PAGE_SIZE
45 #define CONTEXT_SIZE            VTD_PAGE_SIZE
46
47 #define IS_GFX_DEVICE(pdev) ((pdev->class >> 16) == PCI_BASE_CLASS_DISPLAY)
48 #define IS_ISA_DEVICE(pdev) ((pdev->class >> 8) == PCI_CLASS_BRIDGE_ISA)
49
50 #define IOAPIC_RANGE_START      (0xfee00000)
51 #define IOAPIC_RANGE_END        (0xfeefffff)
52 #define IOVA_START_ADDR         (0x1000)
53
54 #define DEFAULT_DOMAIN_ADDRESS_WIDTH 48
55
56 #define DOMAIN_MAX_ADDR(gaw) ((((u64)1) << gaw) - 1)
57
58 #define IOVA_PFN(addr)          ((addr) >> PAGE_SHIFT)
59 #define DMA_32BIT_PFN           IOVA_PFN(DMA_BIT_MASK(32))
60 #define DMA_64BIT_PFN           IOVA_PFN(DMA_BIT_MASK(64))
61
62 /* global iommu list, set NULL for ignored DMAR units */
63 static struct intel_iommu **g_iommus;
64
65 static int rwbf_quirk;
66
67 /*
68  * 0: Present
69  * 1-11: Reserved
70  * 12-63: Context Ptr (12 - (haw-1))
71  * 64-127: Reserved
72  */
73 struct root_entry {
74         u64     val;
75         u64     rsvd1;
76 };
77 #define ROOT_ENTRY_NR (VTD_PAGE_SIZE/sizeof(struct root_entry))
78 static inline bool root_present(struct root_entry *root)
79 {
80         return (root->val & 1);
81 }
82 static inline void set_root_present(struct root_entry *root)
83 {
84         root->val |= 1;
85 }
86 static inline void set_root_value(struct root_entry *root, unsigned long value)
87 {
88         root->val |= value & VTD_PAGE_MASK;
89 }
90
91 static inline struct context_entry *
92 get_context_addr_from_root(struct root_entry *root)
93 {
94         return (struct context_entry *)
95                 (root_present(root)?phys_to_virt(
96                 root->val & VTD_PAGE_MASK) :
97                 NULL);
98 }
99
100 /*
101  * low 64 bits:
102  * 0: present
103  * 1: fault processing disable
104  * 2-3: translation type
105  * 12-63: address space root
106  * high 64 bits:
107  * 0-2: address width
108  * 3-6: aval
109  * 8-23: domain id
110  */
111 struct context_entry {
112         u64 lo;
113         u64 hi;
114 };
115
116 static inline bool context_present(struct context_entry *context)
117 {
118         return (context->lo & 1);
119 }
120 static inline void context_set_present(struct context_entry *context)
121 {
122         context->lo |= 1;
123 }
124
125 static inline void context_set_fault_enable(struct context_entry *context)
126 {
127         context->lo &= (((u64)-1) << 2) | 1;
128 }
129
130 #define CONTEXT_TT_MULTI_LEVEL 0
131
132 static inline void context_set_translation_type(struct context_entry *context,
133                                                 unsigned long value)
134 {
135         context->lo &= (((u64)-1) << 4) | 3;
136         context->lo |= (value & 3) << 2;
137 }
138
139 static inline void context_set_address_root(struct context_entry *context,
140                                             unsigned long value)
141 {
142         context->lo |= value & VTD_PAGE_MASK;
143 }
144
145 static inline void context_set_address_width(struct context_entry *context,
146                                              unsigned long value)
147 {
148         context->hi |= value & 7;
149 }
150
151 static inline void context_set_domain_id(struct context_entry *context,
152                                          unsigned long value)
153 {
154         context->hi |= (value & ((1 << 16) - 1)) << 8;
155 }
156
157 static inline void context_clear_entry(struct context_entry *context)
158 {
159         context->lo = 0;
160         context->hi = 0;
161 }
162
163 /*
164  * 0: readable
165  * 1: writable
166  * 2-6: reserved
167  * 7: super page
168  * 8-10: available
169  * 11: snoop behavior
170  * 12-63: Host physcial address
171  */
172 struct dma_pte {
173         u64 val;
174 };
175
176 static inline void dma_clear_pte(struct dma_pte *pte)
177 {
178         pte->val = 0;
179 }
180
181 static inline void dma_set_pte_readable(struct dma_pte *pte)
182 {
183         pte->val |= DMA_PTE_READ;
184 }
185
186 static inline void dma_set_pte_writable(struct dma_pte *pte)
187 {
188         pte->val |= DMA_PTE_WRITE;
189 }
190
191 static inline void dma_set_pte_snp(struct dma_pte *pte)
192 {
193         pte->val |= DMA_PTE_SNP;
194 }
195
196 static inline void dma_set_pte_prot(struct dma_pte *pte, unsigned long prot)
197 {
198         pte->val = (pte->val & ~3) | (prot & 3);
199 }
200
201 static inline u64 dma_pte_addr(struct dma_pte *pte)
202 {
203         return (pte->val & VTD_PAGE_MASK);
204 }
205
206 static inline void dma_set_pte_addr(struct dma_pte *pte, u64 addr)
207 {
208         pte->val |= (addr & VTD_PAGE_MASK);
209 }
210
211 static inline bool dma_pte_present(struct dma_pte *pte)
212 {
213         return (pte->val & 3) != 0;
214 }
215
216 /* devices under the same p2p bridge are owned in one domain */
217 #define DOMAIN_FLAG_P2P_MULTIPLE_DEVICES (1 << 0)
218
219 /* domain represents a virtual machine, more than one devices
220  * across iommus may be owned in one domain, e.g. kvm guest.
221  */
222 #define DOMAIN_FLAG_VIRTUAL_MACHINE     (1 << 1)
223
224 struct dmar_domain {
225         int     id;                     /* domain id */
226         unsigned long iommu_bmp;        /* bitmap of iommus this domain uses*/
227
228         struct list_head devices;       /* all devices' list */
229         struct iova_domain iovad;       /* iova's that belong to this domain */
230
231         struct dma_pte  *pgd;           /* virtual address */
232         spinlock_t      mapping_lock;   /* page table lock */
233         int             gaw;            /* max guest address width */
234
235         /* adjusted guest address width, 0 is level 2 30-bit */
236         int             agaw;
237
238         int             flags;          /* flags to find out type of domain */
239
240         int             iommu_coherency;/* indicate coherency of iommu access */
241         int             iommu_snooping; /* indicate snooping control feature*/
242         int             iommu_count;    /* reference count of iommu */
243         spinlock_t      iommu_lock;     /* protect iommu set in domain */
244         u64             max_addr;       /* maximum mapped address */
245 };
246
247 /* PCI domain-device relationship */
248 struct device_domain_info {
249         struct list_head link;  /* link to domain siblings */
250         struct list_head global; /* link to global list */
251         int segment;            /* PCI domain */
252         u8 bus;                 /* PCI bus number */
253         u8 devfn;               /* PCI devfn number */
254         struct pci_dev *dev; /* it's NULL for PCIE-to-PCI bridge */
255         struct dmar_domain *domain; /* pointer to domain */
256 };
257
258 static void flush_unmaps_timeout(unsigned long data);
259
260 DEFINE_TIMER(unmap_timer,  flush_unmaps_timeout, 0, 0);
261
262 #define HIGH_WATER_MARK 250
263 struct deferred_flush_tables {
264         int next;
265         struct iova *iova[HIGH_WATER_MARK];
266         struct dmar_domain *domain[HIGH_WATER_MARK];
267 };
268
269 static struct deferred_flush_tables *deferred_flush;
270
271 /* bitmap for indexing intel_iommus */
272 static int g_num_of_iommus;
273
274 static DEFINE_SPINLOCK(async_umap_flush_lock);
275 static LIST_HEAD(unmaps_to_do);
276
277 static int timer_on;
278 static long list_size;
279
280 static void domain_remove_dev_info(struct dmar_domain *domain);
281
282 #ifdef CONFIG_DMAR_DEFAULT_ON
283 int dmar_disabled = 0;
284 #else
285 int dmar_disabled = 1;
286 #endif /*CONFIG_DMAR_DEFAULT_ON*/
287
288 static int __initdata dmar_map_gfx = 1;
289 static int dmar_forcedac;
290 static int intel_iommu_strict;
291
292 #define DUMMY_DEVICE_DOMAIN_INFO ((struct device_domain_info *)(-1))
293 static DEFINE_SPINLOCK(device_domain_lock);
294 static LIST_HEAD(device_domain_list);
295
296 static struct iommu_ops intel_iommu_ops;
297
298 static int __init intel_iommu_setup(char *str)
299 {
300         if (!str)
301                 return -EINVAL;
302         while (*str) {
303                 if (!strncmp(str, "on", 2)) {
304                         dmar_disabled = 0;
305                         printk(KERN_INFO "Intel-IOMMU: enabled\n");
306                 } else if (!strncmp(str, "off", 3)) {
307                         dmar_disabled = 1;
308                         printk(KERN_INFO "Intel-IOMMU: disabled\n");
309                 } else if (!strncmp(str, "igfx_off", 8)) {
310                         dmar_map_gfx = 0;
311                         printk(KERN_INFO
312                                 "Intel-IOMMU: disable GFX device mapping\n");
313                 } else if (!strncmp(str, "forcedac", 8)) {
314                         printk(KERN_INFO
315                                 "Intel-IOMMU: Forcing DAC for PCI devices\n");
316                         dmar_forcedac = 1;
317                 } else if (!strncmp(str, "strict", 6)) {
318                         printk(KERN_INFO
319                                 "Intel-IOMMU: disable batched IOTLB flush\n");
320                         intel_iommu_strict = 1;
321                 }
322
323                 str += strcspn(str, ",");
324                 while (*str == ',')
325                         str++;
326         }
327         return 0;
328 }
329 __setup("intel_iommu=", intel_iommu_setup);
330
331 static struct kmem_cache *iommu_domain_cache;
332 static struct kmem_cache *iommu_devinfo_cache;
333 static struct kmem_cache *iommu_iova_cache;
334
335 static inline void *iommu_kmem_cache_alloc(struct kmem_cache *cachep)
336 {
337         unsigned int flags;
338         void *vaddr;
339
340         /* trying to avoid low memory issues */
341         flags = current->flags & PF_MEMALLOC;
342         current->flags |= PF_MEMALLOC;
343         vaddr = kmem_cache_alloc(cachep, GFP_ATOMIC);
344         current->flags &= (~PF_MEMALLOC | flags);
345         return vaddr;
346 }
347
348
349 static inline void *alloc_pgtable_page(void)
350 {
351         unsigned int flags;
352         void *vaddr;
353
354         /* trying to avoid low memory issues */
355         flags = current->flags & PF_MEMALLOC;
356         current->flags |= PF_MEMALLOC;
357         vaddr = (void *)get_zeroed_page(GFP_ATOMIC);
358         current->flags &= (~PF_MEMALLOC | flags);
359         return vaddr;
360 }
361
362 static inline void free_pgtable_page(void *vaddr)
363 {
364         free_page((unsigned long)vaddr);
365 }
366
367 static inline void *alloc_domain_mem(void)
368 {
369         return iommu_kmem_cache_alloc(iommu_domain_cache);
370 }
371
372 static void free_domain_mem(void *vaddr)
373 {
374         kmem_cache_free(iommu_domain_cache, vaddr);
375 }
376
377 static inline void * alloc_devinfo_mem(void)
378 {
379         return iommu_kmem_cache_alloc(iommu_devinfo_cache);
380 }
381
382 static inline void free_devinfo_mem(void *vaddr)
383 {
384         kmem_cache_free(iommu_devinfo_cache, vaddr);
385 }
386
387 struct iova *alloc_iova_mem(void)
388 {
389         return iommu_kmem_cache_alloc(iommu_iova_cache);
390 }
391
392 void free_iova_mem(struct iova *iova)
393 {
394         kmem_cache_free(iommu_iova_cache, iova);
395 }
396
397
398 static inline int width_to_agaw(int width);
399
400 /* calculate agaw for each iommu.
401  * "SAGAW" may be different across iommus, use a default agaw, and
402  * get a supported less agaw for iommus that don't support the default agaw.
403  */
404 int iommu_calculate_agaw(struct intel_iommu *iommu)
405 {
406         unsigned long sagaw;
407         int agaw = -1;
408
409         sagaw = cap_sagaw(iommu->cap);
410         for (agaw = width_to_agaw(DEFAULT_DOMAIN_ADDRESS_WIDTH);
411              agaw >= 0; agaw--) {
412                 if (test_bit(agaw, &sagaw))
413                         break;
414         }
415
416         return agaw;
417 }
418
419 /* in native case, each domain is related to only one iommu */
420 static struct intel_iommu *domain_get_iommu(struct dmar_domain *domain)
421 {
422         int iommu_id;
423
424         BUG_ON(domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE);
425
426         iommu_id = find_first_bit(&domain->iommu_bmp, g_num_of_iommus);
427         if (iommu_id < 0 || iommu_id >= g_num_of_iommus)
428                 return NULL;
429
430         return g_iommus[iommu_id];
431 }
432
433 static void domain_update_iommu_coherency(struct dmar_domain *domain)
434 {
435         int i;
436
437         domain->iommu_coherency = 1;
438
439         i = find_first_bit(&domain->iommu_bmp, g_num_of_iommus);
440         for (; i < g_num_of_iommus; ) {
441                 if (!ecap_coherent(g_iommus[i]->ecap)) {
442                         domain->iommu_coherency = 0;
443                         break;
444                 }
445                 i = find_next_bit(&domain->iommu_bmp, g_num_of_iommus, i+1);
446         }
447 }
448
449 static void domain_update_iommu_snooping(struct dmar_domain *domain)
450 {
451         int i;
452
453         domain->iommu_snooping = 1;
454
455         i = find_first_bit(&domain->iommu_bmp, g_num_of_iommus);
456         for (; i < g_num_of_iommus; ) {
457                 if (!ecap_sc_support(g_iommus[i]->ecap)) {
458                         domain->iommu_snooping = 0;
459                         break;
460                 }
461                 i = find_next_bit(&domain->iommu_bmp, g_num_of_iommus, i+1);
462         }
463 }
464
465 /* Some capabilities may be different across iommus */
466 static void domain_update_iommu_cap(struct dmar_domain *domain)
467 {
468         domain_update_iommu_coherency(domain);
469         domain_update_iommu_snooping(domain);
470 }
471
472 static struct intel_iommu *device_to_iommu(int segment, u8 bus, u8 devfn)
473 {
474         struct dmar_drhd_unit *drhd = NULL;
475         int i;
476
477         for_each_drhd_unit(drhd) {
478                 if (drhd->ignored)
479                         continue;
480                 if (segment != drhd->segment)
481                         continue;
482
483                 for (i = 0; i < drhd->devices_cnt; i++) {
484                         if (drhd->devices[i] &&
485                             drhd->devices[i]->bus->number == bus &&
486                             drhd->devices[i]->devfn == devfn)
487                                 return drhd->iommu;
488                         if (drhd->devices[i] &&
489                             drhd->devices[i]->subordinate &&
490                             drhd->devices[i]->subordinate->number <= bus &&
491                             drhd->devices[i]->subordinate->subordinate >= bus)
492                                 return drhd->iommu;
493                 }
494
495                 if (drhd->include_all)
496                         return drhd->iommu;
497         }
498
499         return NULL;
500 }
501
502 static void domain_flush_cache(struct dmar_domain *domain,
503                                void *addr, int size)
504 {
505         if (!domain->iommu_coherency)
506                 clflush_cache_range(addr, size);
507 }
508
509 /* Gets context entry for a given bus and devfn */
510 static struct context_entry * device_to_context_entry(struct intel_iommu *iommu,
511                 u8 bus, u8 devfn)
512 {
513         struct root_entry *root;
514         struct context_entry *context;
515         unsigned long phy_addr;
516         unsigned long flags;
517
518         spin_lock_irqsave(&iommu->lock, flags);
519         root = &iommu->root_entry[bus];
520         context = get_context_addr_from_root(root);
521         if (!context) {
522                 context = (struct context_entry *)alloc_pgtable_page();
523                 if (!context) {
524                         spin_unlock_irqrestore(&iommu->lock, flags);
525                         return NULL;
526                 }
527                 __iommu_flush_cache(iommu, (void *)context, CONTEXT_SIZE);
528                 phy_addr = virt_to_phys((void *)context);
529                 set_root_value(root, phy_addr);
530                 set_root_present(root);
531                 __iommu_flush_cache(iommu, root, sizeof(*root));
532         }
533         spin_unlock_irqrestore(&iommu->lock, flags);
534         return &context[devfn];
535 }
536
537 static int device_context_mapped(struct intel_iommu *iommu, u8 bus, u8 devfn)
538 {
539         struct root_entry *root;
540         struct context_entry *context;
541         int ret;
542         unsigned long flags;
543
544         spin_lock_irqsave(&iommu->lock, flags);
545         root = &iommu->root_entry[bus];
546         context = get_context_addr_from_root(root);
547         if (!context) {
548                 ret = 0;
549                 goto out;
550         }
551         ret = context_present(&context[devfn]);
552 out:
553         spin_unlock_irqrestore(&iommu->lock, flags);
554         return ret;
555 }
556
557 static void clear_context_table(struct intel_iommu *iommu, u8 bus, u8 devfn)
558 {
559         struct root_entry *root;
560         struct context_entry *context;
561         unsigned long flags;
562
563         spin_lock_irqsave(&iommu->lock, flags);
564         root = &iommu->root_entry[bus];
565         context = get_context_addr_from_root(root);
566         if (context) {
567                 context_clear_entry(&context[devfn]);
568                 __iommu_flush_cache(iommu, &context[devfn], \
569                         sizeof(*context));
570         }
571         spin_unlock_irqrestore(&iommu->lock, flags);
572 }
573
574 static void free_context_table(struct intel_iommu *iommu)
575 {
576         struct root_entry *root;
577         int i;
578         unsigned long flags;
579         struct context_entry *context;
580
581         spin_lock_irqsave(&iommu->lock, flags);
582         if (!iommu->root_entry) {
583                 goto out;
584         }
585         for (i = 0; i < ROOT_ENTRY_NR; i++) {
586                 root = &iommu->root_entry[i];
587                 context = get_context_addr_from_root(root);
588                 if (context)
589                         free_pgtable_page(context);
590         }
591         free_pgtable_page(iommu->root_entry);
592         iommu->root_entry = NULL;
593 out:
594         spin_unlock_irqrestore(&iommu->lock, flags);
595 }
596
597 /* page table handling */
598 #define LEVEL_STRIDE            (9)
599 #define LEVEL_MASK              (((u64)1 << LEVEL_STRIDE) - 1)
600
601 static inline int agaw_to_level(int agaw)
602 {
603         return agaw + 2;
604 }
605
606 static inline int agaw_to_width(int agaw)
607 {
608         return 30 + agaw * LEVEL_STRIDE;
609
610 }
611
612 static inline int width_to_agaw(int width)
613 {
614         return (width - 30) / LEVEL_STRIDE;
615 }
616
617 static inline unsigned int level_to_offset_bits(int level)
618 {
619         return (12 + (level - 1) * LEVEL_STRIDE);
620 }
621
622 static inline int address_level_offset(u64 addr, int level)
623 {
624         return ((addr >> level_to_offset_bits(level)) & LEVEL_MASK);
625 }
626
627 static inline u64 level_mask(int level)
628 {
629         return ((u64)-1 << level_to_offset_bits(level));
630 }
631
632 static inline u64 level_size(int level)
633 {
634         return ((u64)1 << level_to_offset_bits(level));
635 }
636
637 static inline u64 align_to_level(u64 addr, int level)
638 {
639         return ((addr + level_size(level) - 1) & level_mask(level));
640 }
641
642 static struct dma_pte * addr_to_dma_pte(struct dmar_domain *domain, u64 addr)
643 {
644         int addr_width = agaw_to_width(domain->agaw);
645         struct dma_pte *parent, *pte = NULL;
646         int level = agaw_to_level(domain->agaw);
647         int offset;
648         unsigned long flags;
649
650         BUG_ON(!domain->pgd);
651
652         addr &= (((u64)1) << addr_width) - 1;
653         parent = domain->pgd;
654
655         spin_lock_irqsave(&domain->mapping_lock, flags);
656         while (level > 0) {
657                 void *tmp_page;
658
659                 offset = address_level_offset(addr, level);
660                 pte = &parent[offset];
661                 if (level == 1)
662                         break;
663
664                 if (!dma_pte_present(pte)) {
665                         tmp_page = alloc_pgtable_page();
666
667                         if (!tmp_page) {
668                                 spin_unlock_irqrestore(&domain->mapping_lock,
669                                         flags);
670                                 return NULL;
671                         }
672                         domain_flush_cache(domain, tmp_page, PAGE_SIZE);
673                         dma_set_pte_addr(pte, virt_to_phys(tmp_page));
674                         /*
675                          * high level table always sets r/w, last level page
676                          * table control read/write
677                          */
678                         dma_set_pte_readable(pte);
679                         dma_set_pte_writable(pte);
680                         domain_flush_cache(domain, pte, sizeof(*pte));
681                 }
682                 parent = phys_to_virt(dma_pte_addr(pte));
683                 level--;
684         }
685
686         spin_unlock_irqrestore(&domain->mapping_lock, flags);
687         return pte;
688 }
689
690 /* return address's pte at specific level */
691 static struct dma_pte *dma_addr_level_pte(struct dmar_domain *domain, u64 addr,
692                 int level)
693 {
694         struct dma_pte *parent, *pte = NULL;
695         int total = agaw_to_level(domain->agaw);
696         int offset;
697
698         parent = domain->pgd;
699         while (level <= total) {
700                 offset = address_level_offset(addr, total);
701                 pte = &parent[offset];
702                 if (level == total)
703                         return pte;
704
705                 if (!dma_pte_present(pte))
706                         break;
707                 parent = phys_to_virt(dma_pte_addr(pte));
708                 total--;
709         }
710         return NULL;
711 }
712
713 /* clear one page's page table */
714 static void dma_pte_clear_one(struct dmar_domain *domain, u64 addr)
715 {
716         struct dma_pte *pte = NULL;
717
718         /* get last level pte */
719         pte = dma_addr_level_pte(domain, addr, 1);
720
721         if (pte) {
722                 dma_clear_pte(pte);
723                 domain_flush_cache(domain, pte, sizeof(*pte));
724         }
725 }
726
727 /* clear last level pte, a tlb flush should be followed */
728 static void dma_pte_clear_range(struct dmar_domain *domain, u64 start, u64 end)
729 {
730         int addr_width = agaw_to_width(domain->agaw);
731         int npages;
732
733         start &= (((u64)1) << addr_width) - 1;
734         end &= (((u64)1) << addr_width) - 1;
735         /* in case it's partial page */
736         start &= PAGE_MASK;
737         end = PAGE_ALIGN(end);
738         npages = (end - start) / VTD_PAGE_SIZE;
739
740         /* we don't need lock here, nobody else touches the iova range */
741         while (npages--) {
742                 dma_pte_clear_one(domain, start);
743                 start += VTD_PAGE_SIZE;
744         }
745 }
746
747 /* free page table pages. last level pte should already be cleared */
748 static void dma_pte_free_pagetable(struct dmar_domain *domain,
749         u64 start, u64 end)
750 {
751         int addr_width = agaw_to_width(domain->agaw);
752         struct dma_pte *pte;
753         int total = agaw_to_level(domain->agaw);
754         int level;
755         u64 tmp;
756
757         start &= (((u64)1) << addr_width) - 1;
758         end &= (((u64)1) << addr_width) - 1;
759
760         /* we don't need lock here, nobody else touches the iova range */
761         level = 2;
762         while (level <= total) {
763                 tmp = align_to_level(start, level);
764                 if (tmp >= end || (tmp + level_size(level) > end))
765                         return;
766
767                 while (tmp < end) {
768                         pte = dma_addr_level_pte(domain, tmp, level);
769                         if (pte) {
770                                 free_pgtable_page(
771                                         phys_to_virt(dma_pte_addr(pte)));
772                                 dma_clear_pte(pte);
773                                 domain_flush_cache(domain, pte, sizeof(*pte));
774                         }
775                         tmp += level_size(level);
776                 }
777                 level++;
778         }
779         /* free pgd */
780         if (start == 0 && end >= ((((u64)1) << addr_width) - 1)) {
781                 free_pgtable_page(domain->pgd);
782                 domain->pgd = NULL;
783         }
784 }
785
786 /* iommu handling */
787 static int iommu_alloc_root_entry(struct intel_iommu *iommu)
788 {
789         struct root_entry *root;
790         unsigned long flags;
791
792         root = (struct root_entry *)alloc_pgtable_page();
793         if (!root)
794                 return -ENOMEM;
795
796         __iommu_flush_cache(iommu, root, ROOT_SIZE);
797
798         spin_lock_irqsave(&iommu->lock, flags);
799         iommu->root_entry = root;
800         spin_unlock_irqrestore(&iommu->lock, flags);
801
802         return 0;
803 }
804
805 static void iommu_set_root_entry(struct intel_iommu *iommu)
806 {
807         void *addr;
808         u32 cmd, sts;
809         unsigned long flag;
810
811         addr = iommu->root_entry;
812
813         spin_lock_irqsave(&iommu->register_lock, flag);
814         dmar_writeq(iommu->reg + DMAR_RTADDR_REG, virt_to_phys(addr));
815
816         cmd = iommu->gcmd | DMA_GCMD_SRTP;
817         writel(cmd, iommu->reg + DMAR_GCMD_REG);
818
819         /* Make sure hardware complete it */
820         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
821                 readl, (sts & DMA_GSTS_RTPS), sts);
822
823         spin_unlock_irqrestore(&iommu->register_lock, flag);
824 }
825
826 static void iommu_flush_write_buffer(struct intel_iommu *iommu)
827 {
828         u32 val;
829         unsigned long flag;
830
831         if (!rwbf_quirk && !cap_rwbf(iommu->cap))
832                 return;
833         val = iommu->gcmd | DMA_GCMD_WBF;
834
835         spin_lock_irqsave(&iommu->register_lock, flag);
836         writel(val, iommu->reg + DMAR_GCMD_REG);
837
838         /* Make sure hardware complete it */
839         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
840                         readl, (!(val & DMA_GSTS_WBFS)), val);
841
842         spin_unlock_irqrestore(&iommu->register_lock, flag);
843 }
844
845 /* return value determine if we need a write buffer flush */
846 static int __iommu_flush_context(struct intel_iommu *iommu,
847         u16 did, u16 source_id, u8 function_mask, u64 type,
848         int non_present_entry_flush)
849 {
850         u64 val = 0;
851         unsigned long flag;
852
853         /*
854          * In the non-present entry flush case, if hardware doesn't cache
855          * non-present entry we do nothing and if hardware cache non-present
856          * entry, we flush entries of domain 0 (the domain id is used to cache
857          * any non-present entries)
858          */
859         if (non_present_entry_flush) {
860                 if (!cap_caching_mode(iommu->cap))
861                         return 1;
862                 else
863                         did = 0;
864         }
865
866         switch (type) {
867         case DMA_CCMD_GLOBAL_INVL:
868                 val = DMA_CCMD_GLOBAL_INVL;
869                 break;
870         case DMA_CCMD_DOMAIN_INVL:
871                 val = DMA_CCMD_DOMAIN_INVL|DMA_CCMD_DID(did);
872                 break;
873         case DMA_CCMD_DEVICE_INVL:
874                 val = DMA_CCMD_DEVICE_INVL|DMA_CCMD_DID(did)
875                         | DMA_CCMD_SID(source_id) | DMA_CCMD_FM(function_mask);
876                 break;
877         default:
878                 BUG();
879         }
880         val |= DMA_CCMD_ICC;
881
882         spin_lock_irqsave(&iommu->register_lock, flag);
883         dmar_writeq(iommu->reg + DMAR_CCMD_REG, val);
884
885         /* Make sure hardware complete it */
886         IOMMU_WAIT_OP(iommu, DMAR_CCMD_REG,
887                 dmar_readq, (!(val & DMA_CCMD_ICC)), val);
888
889         spin_unlock_irqrestore(&iommu->register_lock, flag);
890
891         /* flush context entry will implicitly flush write buffer */
892         return 0;
893 }
894
895 /* return value determine if we need a write buffer flush */
896 static int __iommu_flush_iotlb(struct intel_iommu *iommu, u16 did,
897         u64 addr, unsigned int size_order, u64 type,
898         int non_present_entry_flush)
899 {
900         int tlb_offset = ecap_iotlb_offset(iommu->ecap);
901         u64 val = 0, val_iva = 0;
902         unsigned long flag;
903
904         /*
905          * In the non-present entry flush case, if hardware doesn't cache
906          * non-present entry we do nothing and if hardware cache non-present
907          * entry, we flush entries of domain 0 (the domain id is used to cache
908          * any non-present entries)
909          */
910         if (non_present_entry_flush) {
911                 if (!cap_caching_mode(iommu->cap))
912                         return 1;
913                 else
914                         did = 0;
915         }
916
917         switch (type) {
918         case DMA_TLB_GLOBAL_FLUSH:
919                 /* global flush doesn't need set IVA_REG */
920                 val = DMA_TLB_GLOBAL_FLUSH|DMA_TLB_IVT;
921                 break;
922         case DMA_TLB_DSI_FLUSH:
923                 val = DMA_TLB_DSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
924                 break;
925         case DMA_TLB_PSI_FLUSH:
926                 val = DMA_TLB_PSI_FLUSH|DMA_TLB_IVT|DMA_TLB_DID(did);
927                 /* Note: always flush non-leaf currently */
928                 val_iva = size_order | addr;
929                 break;
930         default:
931                 BUG();
932         }
933         /* Note: set drain read/write */
934 #if 0
935         /*
936          * This is probably to be super secure.. Looks like we can
937          * ignore it without any impact.
938          */
939         if (cap_read_drain(iommu->cap))
940                 val |= DMA_TLB_READ_DRAIN;
941 #endif
942         if (cap_write_drain(iommu->cap))
943                 val |= DMA_TLB_WRITE_DRAIN;
944
945         spin_lock_irqsave(&iommu->register_lock, flag);
946         /* Note: Only uses first TLB reg currently */
947         if (val_iva)
948                 dmar_writeq(iommu->reg + tlb_offset, val_iva);
949         dmar_writeq(iommu->reg + tlb_offset + 8, val);
950
951         /* Make sure hardware complete it */
952         IOMMU_WAIT_OP(iommu, tlb_offset + 8,
953                 dmar_readq, (!(val & DMA_TLB_IVT)), val);
954
955         spin_unlock_irqrestore(&iommu->register_lock, flag);
956
957         /* check IOTLB invalidation granularity */
958         if (DMA_TLB_IAIG(val) == 0)
959                 printk(KERN_ERR"IOMMU: flush IOTLB failed\n");
960         if (DMA_TLB_IAIG(val) != DMA_TLB_IIRG(type))
961                 pr_debug("IOMMU: tlb flush request %Lx, actual %Lx\n",
962                         (unsigned long long)DMA_TLB_IIRG(type),
963                         (unsigned long long)DMA_TLB_IAIG(val));
964         /* flush iotlb entry will implicitly flush write buffer */
965         return 0;
966 }
967
968 static int iommu_flush_iotlb_psi(struct intel_iommu *iommu, u16 did,
969         u64 addr, unsigned int pages, int non_present_entry_flush)
970 {
971         unsigned int mask;
972
973         BUG_ON(addr & (~VTD_PAGE_MASK));
974         BUG_ON(pages == 0);
975
976         /* Fallback to domain selective flush if no PSI support */
977         if (!cap_pgsel_inv(iommu->cap))
978                 return iommu->flush.flush_iotlb(iommu, did, 0, 0,
979                                                 DMA_TLB_DSI_FLUSH,
980                                                 non_present_entry_flush);
981
982         /*
983          * PSI requires page size to be 2 ^ x, and the base address is naturally
984          * aligned to the size
985          */
986         mask = ilog2(__roundup_pow_of_two(pages));
987         /* Fallback to domain selective flush if size is too big */
988         if (mask > cap_max_amask_val(iommu->cap))
989                 return iommu->flush.flush_iotlb(iommu, did, 0, 0,
990                         DMA_TLB_DSI_FLUSH, non_present_entry_flush);
991
992         return iommu->flush.flush_iotlb(iommu, did, addr, mask,
993                                         DMA_TLB_PSI_FLUSH,
994                                         non_present_entry_flush);
995 }
996
997 static void iommu_disable_protect_mem_regions(struct intel_iommu *iommu)
998 {
999         u32 pmen;
1000         unsigned long flags;
1001
1002         spin_lock_irqsave(&iommu->register_lock, flags);
1003         pmen = readl(iommu->reg + DMAR_PMEN_REG);
1004         pmen &= ~DMA_PMEN_EPM;
1005         writel(pmen, iommu->reg + DMAR_PMEN_REG);
1006
1007         /* wait for the protected region status bit to clear */
1008         IOMMU_WAIT_OP(iommu, DMAR_PMEN_REG,
1009                 readl, !(pmen & DMA_PMEN_PRS), pmen);
1010
1011         spin_unlock_irqrestore(&iommu->register_lock, flags);
1012 }
1013
1014 static int iommu_enable_translation(struct intel_iommu *iommu)
1015 {
1016         u32 sts;
1017         unsigned long flags;
1018
1019         spin_lock_irqsave(&iommu->register_lock, flags);
1020         writel(iommu->gcmd|DMA_GCMD_TE, iommu->reg + DMAR_GCMD_REG);
1021
1022         /* Make sure hardware complete it */
1023         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1024                 readl, (sts & DMA_GSTS_TES), sts);
1025
1026         iommu->gcmd |= DMA_GCMD_TE;
1027         spin_unlock_irqrestore(&iommu->register_lock, flags);
1028         return 0;
1029 }
1030
1031 static int iommu_disable_translation(struct intel_iommu *iommu)
1032 {
1033         u32 sts;
1034         unsigned long flag;
1035
1036         spin_lock_irqsave(&iommu->register_lock, flag);
1037         iommu->gcmd &= ~DMA_GCMD_TE;
1038         writel(iommu->gcmd, iommu->reg + DMAR_GCMD_REG);
1039
1040         /* Make sure hardware complete it */
1041         IOMMU_WAIT_OP(iommu, DMAR_GSTS_REG,
1042                 readl, (!(sts & DMA_GSTS_TES)), sts);
1043
1044         spin_unlock_irqrestore(&iommu->register_lock, flag);
1045         return 0;
1046 }
1047
1048
1049 static int iommu_init_domains(struct intel_iommu *iommu)
1050 {
1051         unsigned long ndomains;
1052         unsigned long nlongs;
1053
1054         ndomains = cap_ndoms(iommu->cap);
1055         pr_debug("Number of Domains supportd <%ld>\n", ndomains);
1056         nlongs = BITS_TO_LONGS(ndomains);
1057
1058         /* TBD: there might be 64K domains,
1059          * consider other allocation for future chip
1060          */
1061         iommu->domain_ids = kcalloc(nlongs, sizeof(unsigned long), GFP_KERNEL);
1062         if (!iommu->domain_ids) {
1063                 printk(KERN_ERR "Allocating domain id array failed\n");
1064                 return -ENOMEM;
1065         }
1066         iommu->domains = kcalloc(ndomains, sizeof(struct dmar_domain *),
1067                         GFP_KERNEL);
1068         if (!iommu->domains) {
1069                 printk(KERN_ERR "Allocating domain array failed\n");
1070                 kfree(iommu->domain_ids);
1071                 return -ENOMEM;
1072         }
1073
1074         spin_lock_init(&iommu->lock);
1075
1076         /*
1077          * if Caching mode is set, then invalid translations are tagged
1078          * with domainid 0. Hence we need to pre-allocate it.
1079          */
1080         if (cap_caching_mode(iommu->cap))
1081                 set_bit(0, iommu->domain_ids);
1082         return 0;
1083 }
1084
1085
1086 static void domain_exit(struct dmar_domain *domain);
1087 static void vm_domain_exit(struct dmar_domain *domain);
1088
1089 void free_dmar_iommu(struct intel_iommu *iommu)
1090 {
1091         struct dmar_domain *domain;
1092         int i;
1093         unsigned long flags;
1094
1095         i = find_first_bit(iommu->domain_ids, cap_ndoms(iommu->cap));
1096         for (; i < cap_ndoms(iommu->cap); ) {
1097                 domain = iommu->domains[i];
1098                 clear_bit(i, iommu->domain_ids);
1099
1100                 spin_lock_irqsave(&domain->iommu_lock, flags);
1101                 if (--domain->iommu_count == 0) {
1102                         if (domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE)
1103                                 vm_domain_exit(domain);
1104                         else
1105                                 domain_exit(domain);
1106                 }
1107                 spin_unlock_irqrestore(&domain->iommu_lock, flags);
1108
1109                 i = find_next_bit(iommu->domain_ids,
1110                         cap_ndoms(iommu->cap), i+1);
1111         }
1112
1113         if (iommu->gcmd & DMA_GCMD_TE)
1114                 iommu_disable_translation(iommu);
1115
1116         if (iommu->irq) {
1117                 set_irq_data(iommu->irq, NULL);
1118                 /* This will mask the irq */
1119                 free_irq(iommu->irq, iommu);
1120                 destroy_irq(iommu->irq);
1121         }
1122
1123         kfree(iommu->domains);
1124         kfree(iommu->domain_ids);
1125
1126         g_iommus[iommu->seq_id] = NULL;
1127
1128         /* if all iommus are freed, free g_iommus */
1129         for (i = 0; i < g_num_of_iommus; i++) {
1130                 if (g_iommus[i])
1131                         break;
1132         }
1133
1134         if (i == g_num_of_iommus)
1135                 kfree(g_iommus);
1136
1137         /* free context mapping */
1138         free_context_table(iommu);
1139 }
1140
1141 static struct dmar_domain * iommu_alloc_domain(struct intel_iommu *iommu)
1142 {
1143         unsigned long num;
1144         unsigned long ndomains;
1145         struct dmar_domain *domain;
1146         unsigned long flags;
1147
1148         domain = alloc_domain_mem();
1149         if (!domain)
1150                 return NULL;
1151
1152         ndomains = cap_ndoms(iommu->cap);
1153
1154         spin_lock_irqsave(&iommu->lock, flags);
1155         num = find_first_zero_bit(iommu->domain_ids, ndomains);
1156         if (num >= ndomains) {
1157                 spin_unlock_irqrestore(&iommu->lock, flags);
1158                 free_domain_mem(domain);
1159                 printk(KERN_ERR "IOMMU: no free domain ids\n");
1160                 return NULL;
1161         }
1162
1163         set_bit(num, iommu->domain_ids);
1164         domain->id = num;
1165         memset(&domain->iommu_bmp, 0, sizeof(unsigned long));
1166         set_bit(iommu->seq_id, &domain->iommu_bmp);
1167         domain->flags = 0;
1168         iommu->domains[num] = domain;
1169         spin_unlock_irqrestore(&iommu->lock, flags);
1170
1171         return domain;
1172 }
1173
1174 static void iommu_free_domain(struct dmar_domain *domain)
1175 {
1176         unsigned long flags;
1177         struct intel_iommu *iommu;
1178
1179         iommu = domain_get_iommu(domain);
1180
1181         spin_lock_irqsave(&iommu->lock, flags);
1182         clear_bit(domain->id, iommu->domain_ids);
1183         spin_unlock_irqrestore(&iommu->lock, flags);
1184 }
1185
1186 static struct iova_domain reserved_iova_list;
1187 static struct lock_class_key reserved_alloc_key;
1188 static struct lock_class_key reserved_rbtree_key;
1189
1190 static void dmar_init_reserved_ranges(void)
1191 {
1192         struct pci_dev *pdev = NULL;
1193         struct iova *iova;
1194         int i;
1195         u64 addr, size;
1196
1197         init_iova_domain(&reserved_iova_list, DMA_32BIT_PFN);
1198
1199         lockdep_set_class(&reserved_iova_list.iova_alloc_lock,
1200                 &reserved_alloc_key);
1201         lockdep_set_class(&reserved_iova_list.iova_rbtree_lock,
1202                 &reserved_rbtree_key);
1203
1204         /* IOAPIC ranges shouldn't be accessed by DMA */
1205         iova = reserve_iova(&reserved_iova_list, IOVA_PFN(IOAPIC_RANGE_START),
1206                 IOVA_PFN(IOAPIC_RANGE_END));
1207         if (!iova)
1208                 printk(KERN_ERR "Reserve IOAPIC range failed\n");
1209
1210         /* Reserve all PCI MMIO to avoid peer-to-peer access */
1211         for_each_pci_dev(pdev) {
1212                 struct resource *r;
1213
1214                 for (i = 0; i < PCI_NUM_RESOURCES; i++) {
1215                         r = &pdev->resource[i];
1216                         if (!r->flags || !(r->flags & IORESOURCE_MEM))
1217                                 continue;
1218                         addr = r->start;
1219                         addr &= PAGE_MASK;
1220                         size = r->end - addr;
1221                         size = PAGE_ALIGN(size);
1222                         iova = reserve_iova(&reserved_iova_list, IOVA_PFN(addr),
1223                                 IOVA_PFN(size + addr) - 1);
1224                         if (!iova)
1225                                 printk(KERN_ERR "Reserve iova failed\n");
1226                 }
1227         }
1228
1229 }
1230
1231 static void domain_reserve_special_ranges(struct dmar_domain *domain)
1232 {
1233         copy_reserved_iova(&reserved_iova_list, &domain->iovad);
1234 }
1235
1236 static inline int guestwidth_to_adjustwidth(int gaw)
1237 {
1238         int agaw;
1239         int r = (gaw - 12) % 9;
1240
1241         if (r == 0)
1242                 agaw = gaw;
1243         else
1244                 agaw = gaw + 9 - r;
1245         if (agaw > 64)
1246                 agaw = 64;
1247         return agaw;
1248 }
1249
1250 static int domain_init(struct dmar_domain *domain, int guest_width)
1251 {
1252         struct intel_iommu *iommu;
1253         int adjust_width, agaw;
1254         unsigned long sagaw;
1255
1256         init_iova_domain(&domain->iovad, DMA_32BIT_PFN);
1257         spin_lock_init(&domain->mapping_lock);
1258         spin_lock_init(&domain->iommu_lock);
1259
1260         domain_reserve_special_ranges(domain);
1261
1262         /* calculate AGAW */
1263         iommu = domain_get_iommu(domain);
1264         if (guest_width > cap_mgaw(iommu->cap))
1265                 guest_width = cap_mgaw(iommu->cap);
1266         domain->gaw = guest_width;
1267         adjust_width = guestwidth_to_adjustwidth(guest_width);
1268         agaw = width_to_agaw(adjust_width);
1269         sagaw = cap_sagaw(iommu->cap);
1270         if (!test_bit(agaw, &sagaw)) {
1271                 /* hardware doesn't support it, choose a bigger one */
1272                 pr_debug("IOMMU: hardware doesn't support agaw %d\n", agaw);
1273                 agaw = find_next_bit(&sagaw, 5, agaw);
1274                 if (agaw >= 5)
1275                         return -ENODEV;
1276         }
1277         domain->agaw = agaw;
1278         INIT_LIST_HEAD(&domain->devices);
1279
1280         if (ecap_coherent(iommu->ecap))
1281                 domain->iommu_coherency = 1;
1282         else
1283                 domain->iommu_coherency = 0;
1284
1285         if (ecap_sc_support(iommu->ecap))
1286                 domain->iommu_snooping = 1;
1287         else
1288                 domain->iommu_snooping = 0;
1289
1290         domain->iommu_count = 1;
1291
1292         /* always allocate the top pgd */
1293         domain->pgd = (struct dma_pte *)alloc_pgtable_page();
1294         if (!domain->pgd)
1295                 return -ENOMEM;
1296         __iommu_flush_cache(iommu, domain->pgd, PAGE_SIZE);
1297         return 0;
1298 }
1299
1300 static void domain_exit(struct dmar_domain *domain)
1301 {
1302         u64 end;
1303
1304         /* Domain 0 is reserved, so dont process it */
1305         if (!domain)
1306                 return;
1307
1308         domain_remove_dev_info(domain);
1309         /* destroy iovas */
1310         put_iova_domain(&domain->iovad);
1311         end = DOMAIN_MAX_ADDR(domain->gaw);
1312         end = end & (~PAGE_MASK);
1313
1314         /* clear ptes */
1315         dma_pte_clear_range(domain, 0, end);
1316
1317         /* free page tables */
1318         dma_pte_free_pagetable(domain, 0, end);
1319
1320         iommu_free_domain(domain);
1321         free_domain_mem(domain);
1322 }
1323
1324 static int domain_context_mapping_one(struct dmar_domain *domain,
1325                                       int segment, u8 bus, u8 devfn)
1326 {
1327         struct context_entry *context;
1328         unsigned long flags;
1329         struct intel_iommu *iommu;
1330         struct dma_pte *pgd;
1331         unsigned long num;
1332         unsigned long ndomains;
1333         int id;
1334         int agaw;
1335
1336         pr_debug("Set context mapping for %02x:%02x.%d\n",
1337                 bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
1338         BUG_ON(!domain->pgd);
1339
1340         iommu = device_to_iommu(segment, bus, devfn);
1341         if (!iommu)
1342                 return -ENODEV;
1343
1344         context = device_to_context_entry(iommu, bus, devfn);
1345         if (!context)
1346                 return -ENOMEM;
1347         spin_lock_irqsave(&iommu->lock, flags);
1348         if (context_present(context)) {
1349                 spin_unlock_irqrestore(&iommu->lock, flags);
1350                 return 0;
1351         }
1352
1353         id = domain->id;
1354         pgd = domain->pgd;
1355
1356         if (domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE) {
1357                 int found = 0;
1358
1359                 /* find an available domain id for this device in iommu */
1360                 ndomains = cap_ndoms(iommu->cap);
1361                 num = find_first_bit(iommu->domain_ids, ndomains);
1362                 for (; num < ndomains; ) {
1363                         if (iommu->domains[num] == domain) {
1364                                 id = num;
1365                                 found = 1;
1366                                 break;
1367                         }
1368                         num = find_next_bit(iommu->domain_ids,
1369                                             cap_ndoms(iommu->cap), num+1);
1370                 }
1371
1372                 if (found == 0) {
1373                         num = find_first_zero_bit(iommu->domain_ids, ndomains);
1374                         if (num >= ndomains) {
1375                                 spin_unlock_irqrestore(&iommu->lock, flags);
1376                                 printk(KERN_ERR "IOMMU: no free domain ids\n");
1377                                 return -EFAULT;
1378                         }
1379
1380                         set_bit(num, iommu->domain_ids);
1381                         iommu->domains[num] = domain;
1382                         id = num;
1383                 }
1384
1385                 /* Skip top levels of page tables for
1386                  * iommu which has less agaw than default.
1387                  */
1388                 for (agaw = domain->agaw; agaw != iommu->agaw; agaw--) {
1389                         pgd = phys_to_virt(dma_pte_addr(pgd));
1390                         if (!dma_pte_present(pgd)) {
1391                                 spin_unlock_irqrestore(&iommu->lock, flags);
1392                                 return -ENOMEM;
1393                         }
1394                 }
1395         }
1396
1397         context_set_domain_id(context, id);
1398         context_set_address_width(context, iommu->agaw);
1399         context_set_address_root(context, virt_to_phys(pgd));
1400         context_set_translation_type(context, CONTEXT_TT_MULTI_LEVEL);
1401         context_set_fault_enable(context);
1402         context_set_present(context);
1403         domain_flush_cache(domain, context, sizeof(*context));
1404
1405         /* it's a non-present to present mapping */
1406         if (iommu->flush.flush_context(iommu, domain->id,
1407                 (((u16)bus) << 8) | devfn, DMA_CCMD_MASK_NOBIT,
1408                 DMA_CCMD_DEVICE_INVL, 1))
1409                 iommu_flush_write_buffer(iommu);
1410         else
1411                 iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_DSI_FLUSH, 0);
1412
1413         spin_unlock_irqrestore(&iommu->lock, flags);
1414
1415         spin_lock_irqsave(&domain->iommu_lock, flags);
1416         if (!test_and_set_bit(iommu->seq_id, &domain->iommu_bmp)) {
1417                 domain->iommu_count++;
1418                 domain_update_iommu_cap(domain);
1419         }
1420         spin_unlock_irqrestore(&domain->iommu_lock, flags);
1421         return 0;
1422 }
1423
1424 static int
1425 domain_context_mapping(struct dmar_domain *domain, struct pci_dev *pdev)
1426 {
1427         int ret;
1428         struct pci_dev *tmp, *parent;
1429
1430         ret = domain_context_mapping_one(domain, pci_domain_nr(pdev->bus),
1431                                          pdev->bus->number, pdev->devfn);
1432         if (ret)
1433                 return ret;
1434
1435         /* dependent device mapping */
1436         tmp = pci_find_upstream_pcie_bridge(pdev);
1437         if (!tmp)
1438                 return 0;
1439         /* Secondary interface's bus number and devfn 0 */
1440         parent = pdev->bus->self;
1441         while (parent != tmp) {
1442                 ret = domain_context_mapping_one(domain,
1443                                                  pci_domain_nr(parent->bus),
1444                                                  parent->bus->number,
1445                                                  parent->devfn);
1446                 if (ret)
1447                         return ret;
1448                 parent = parent->bus->self;
1449         }
1450         if (tmp->is_pcie) /* this is a PCIE-to-PCI bridge */
1451                 return domain_context_mapping_one(domain,
1452                                         pci_domain_nr(tmp->subordinate),
1453                                         tmp->subordinate->number, 0);
1454         else /* this is a legacy PCI bridge */
1455                 return domain_context_mapping_one(domain,
1456                                                   pci_domain_nr(tmp->bus),
1457                                                   tmp->bus->number,
1458                                                   tmp->devfn);
1459 }
1460
1461 static int domain_context_mapped(struct pci_dev *pdev)
1462 {
1463         int ret;
1464         struct pci_dev *tmp, *parent;
1465         struct intel_iommu *iommu;
1466
1467         iommu = device_to_iommu(pci_domain_nr(pdev->bus), pdev->bus->number,
1468                                 pdev->devfn);
1469         if (!iommu)
1470                 return -ENODEV;
1471
1472         ret = device_context_mapped(iommu, pdev->bus->number, pdev->devfn);
1473         if (!ret)
1474                 return ret;
1475         /* dependent device mapping */
1476         tmp = pci_find_upstream_pcie_bridge(pdev);
1477         if (!tmp)
1478                 return ret;
1479         /* Secondary interface's bus number and devfn 0 */
1480         parent = pdev->bus->self;
1481         while (parent != tmp) {
1482                 ret = device_context_mapped(iommu, parent->bus->number,
1483                                             parent->devfn);
1484                 if (!ret)
1485                         return ret;
1486                 parent = parent->bus->self;
1487         }
1488         if (tmp->is_pcie)
1489                 return device_context_mapped(iommu, tmp->subordinate->number,
1490                                              0);
1491         else
1492                 return device_context_mapped(iommu, tmp->bus->number,
1493                                              tmp->devfn);
1494 }
1495
1496 static int
1497 domain_page_mapping(struct dmar_domain *domain, dma_addr_t iova,
1498                         u64 hpa, size_t size, int prot)
1499 {
1500         u64 start_pfn, end_pfn;
1501         struct dma_pte *pte;
1502         int index;
1503         int addr_width = agaw_to_width(domain->agaw);
1504
1505         hpa &= (((u64)1) << addr_width) - 1;
1506
1507         if ((prot & (DMA_PTE_READ|DMA_PTE_WRITE)) == 0)
1508                 return -EINVAL;
1509         iova &= PAGE_MASK;
1510         start_pfn = ((u64)hpa) >> VTD_PAGE_SHIFT;
1511         end_pfn = (VTD_PAGE_ALIGN(((u64)hpa) + size)) >> VTD_PAGE_SHIFT;
1512         index = 0;
1513         while (start_pfn < end_pfn) {
1514                 pte = addr_to_dma_pte(domain, iova + VTD_PAGE_SIZE * index);
1515                 if (!pte)
1516                         return -ENOMEM;
1517                 /* We don't need lock here, nobody else
1518                  * touches the iova range
1519                  */
1520                 BUG_ON(dma_pte_addr(pte));
1521                 dma_set_pte_addr(pte, start_pfn << VTD_PAGE_SHIFT);
1522                 dma_set_pte_prot(pte, prot);
1523                 if (prot & DMA_PTE_SNP)
1524                         dma_set_pte_snp(pte);
1525                 domain_flush_cache(domain, pte, sizeof(*pte));
1526                 start_pfn++;
1527                 index++;
1528         }
1529         return 0;
1530 }
1531
1532 static void iommu_detach_dev(struct intel_iommu *iommu, u8 bus, u8 devfn)
1533 {
1534         if (!iommu)
1535                 return;
1536
1537         clear_context_table(iommu, bus, devfn);
1538         iommu->flush.flush_context(iommu, 0, 0, 0,
1539                                            DMA_CCMD_GLOBAL_INVL, 0);
1540         iommu->flush.flush_iotlb(iommu, 0, 0, 0,
1541                                          DMA_TLB_GLOBAL_FLUSH, 0);
1542 }
1543
1544 static void domain_remove_dev_info(struct dmar_domain *domain)
1545 {
1546         struct device_domain_info *info;
1547         unsigned long flags;
1548         struct intel_iommu *iommu;
1549
1550         spin_lock_irqsave(&device_domain_lock, flags);
1551         while (!list_empty(&domain->devices)) {
1552                 info = list_entry(domain->devices.next,
1553                         struct device_domain_info, link);
1554                 list_del(&info->link);
1555                 list_del(&info->global);
1556                 if (info->dev)
1557                         info->dev->dev.archdata.iommu = NULL;
1558                 spin_unlock_irqrestore(&device_domain_lock, flags);
1559
1560                 iommu = device_to_iommu(info->segment, info->bus, info->devfn);
1561                 iommu_detach_dev(iommu, info->bus, info->devfn);
1562                 free_devinfo_mem(info);
1563
1564                 spin_lock_irqsave(&device_domain_lock, flags);
1565         }
1566         spin_unlock_irqrestore(&device_domain_lock, flags);
1567 }
1568
1569 /*
1570  * find_domain
1571  * Note: we use struct pci_dev->dev.archdata.iommu stores the info
1572  */
1573 static struct dmar_domain *
1574 find_domain(struct pci_dev *pdev)
1575 {
1576         struct device_domain_info *info;
1577
1578         /* No lock here, assumes no domain exit in normal case */
1579         info = pdev->dev.archdata.iommu;
1580         if (info)
1581                 return info->domain;
1582         return NULL;
1583 }
1584
1585 /* domain is initialized */
1586 static struct dmar_domain *get_domain_for_dev(struct pci_dev *pdev, int gaw)
1587 {
1588         struct dmar_domain *domain, *found = NULL;
1589         struct intel_iommu *iommu;
1590         struct dmar_drhd_unit *drhd;
1591         struct device_domain_info *info, *tmp;
1592         struct pci_dev *dev_tmp;
1593         unsigned long flags;
1594         int bus = 0, devfn = 0;
1595         int segment;
1596
1597         domain = find_domain(pdev);
1598         if (domain)
1599                 return domain;
1600
1601         segment = pci_domain_nr(pdev->bus);
1602
1603         dev_tmp = pci_find_upstream_pcie_bridge(pdev);
1604         if (dev_tmp) {
1605                 if (dev_tmp->is_pcie) {
1606                         bus = dev_tmp->subordinate->number;
1607                         devfn = 0;
1608                 } else {
1609                         bus = dev_tmp->bus->number;
1610                         devfn = dev_tmp->devfn;
1611                 }
1612                 spin_lock_irqsave(&device_domain_lock, flags);
1613                 list_for_each_entry(info, &device_domain_list, global) {
1614                         if (info->segment == segment &&
1615                             info->bus == bus && info->devfn == devfn) {
1616                                 found = info->domain;
1617                                 break;
1618                         }
1619                 }
1620                 spin_unlock_irqrestore(&device_domain_lock, flags);
1621                 /* pcie-pci bridge already has a domain, uses it */
1622                 if (found) {
1623                         domain = found;
1624                         goto found_domain;
1625                 }
1626         }
1627
1628         /* Allocate new domain for the device */
1629         drhd = dmar_find_matched_drhd_unit(pdev);
1630         if (!drhd) {
1631                 printk(KERN_ERR "IOMMU: can't find DMAR for device %s\n",
1632                         pci_name(pdev));
1633                 return NULL;
1634         }
1635         iommu = drhd->iommu;
1636
1637         domain = iommu_alloc_domain(iommu);
1638         if (!domain)
1639                 goto error;
1640
1641         if (domain_init(domain, gaw)) {
1642                 domain_exit(domain);
1643                 goto error;
1644         }
1645
1646         /* register pcie-to-pci device */
1647         if (dev_tmp) {
1648                 info = alloc_devinfo_mem();
1649                 if (!info) {
1650                         domain_exit(domain);
1651                         goto error;
1652                 }
1653                 info->segment = segment;
1654                 info->bus = bus;
1655                 info->devfn = devfn;
1656                 info->dev = NULL;
1657                 info->domain = domain;
1658                 /* This domain is shared by devices under p2p bridge */
1659                 domain->flags |= DOMAIN_FLAG_P2P_MULTIPLE_DEVICES;
1660
1661                 /* pcie-to-pci bridge already has a domain, uses it */
1662                 found = NULL;
1663                 spin_lock_irqsave(&device_domain_lock, flags);
1664                 list_for_each_entry(tmp, &device_domain_list, global) {
1665                         if (tmp->segment == segment &&
1666                             tmp->bus == bus && tmp->devfn == devfn) {
1667                                 found = tmp->domain;
1668                                 break;
1669                         }
1670                 }
1671                 if (found) {
1672                         free_devinfo_mem(info);
1673                         domain_exit(domain);
1674                         domain = found;
1675                 } else {
1676                         list_add(&info->link, &domain->devices);
1677                         list_add(&info->global, &device_domain_list);
1678                 }
1679                 spin_unlock_irqrestore(&device_domain_lock, flags);
1680         }
1681
1682 found_domain:
1683         info = alloc_devinfo_mem();
1684         if (!info)
1685                 goto error;
1686         info->segment = segment;
1687         info->bus = pdev->bus->number;
1688         info->devfn = pdev->devfn;
1689         info->dev = pdev;
1690         info->domain = domain;
1691         spin_lock_irqsave(&device_domain_lock, flags);
1692         /* somebody is fast */
1693         found = find_domain(pdev);
1694         if (found != NULL) {
1695                 spin_unlock_irqrestore(&device_domain_lock, flags);
1696                 if (found != domain) {
1697                         domain_exit(domain);
1698                         domain = found;
1699                 }
1700                 free_devinfo_mem(info);
1701                 return domain;
1702         }
1703         list_add(&info->link, &domain->devices);
1704         list_add(&info->global, &device_domain_list);
1705         pdev->dev.archdata.iommu = info;
1706         spin_unlock_irqrestore(&device_domain_lock, flags);
1707         return domain;
1708 error:
1709         /* recheck it here, maybe others set it */
1710         return find_domain(pdev);
1711 }
1712
1713 static int iommu_prepare_identity_map(struct pci_dev *pdev,
1714                                       unsigned long long start,
1715                                       unsigned long long end)
1716 {
1717         struct dmar_domain *domain;
1718         unsigned long size;
1719         unsigned long long base;
1720         int ret;
1721
1722         printk(KERN_INFO
1723                 "IOMMU: Setting identity map for device %s [0x%Lx - 0x%Lx]\n",
1724                 pci_name(pdev), start, end);
1725         /* page table init */
1726         domain = get_domain_for_dev(pdev, DEFAULT_DOMAIN_ADDRESS_WIDTH);
1727         if (!domain)
1728                 return -ENOMEM;
1729
1730         /* The address might not be aligned */
1731         base = start & PAGE_MASK;
1732         size = end - base;
1733         size = PAGE_ALIGN(size);
1734         if (!reserve_iova(&domain->iovad, IOVA_PFN(base),
1735                         IOVA_PFN(base + size) - 1)) {
1736                 printk(KERN_ERR "IOMMU: reserve iova failed\n");
1737                 ret = -ENOMEM;
1738                 goto error;
1739         }
1740
1741         pr_debug("Mapping reserved region %lx@%llx for %s\n",
1742                 size, base, pci_name(pdev));
1743         /*
1744          * RMRR range might have overlap with physical memory range,
1745          * clear it first
1746          */
1747         dma_pte_clear_range(domain, base, base + size);
1748
1749         ret = domain_page_mapping(domain, base, base, size,
1750                 DMA_PTE_READ|DMA_PTE_WRITE);
1751         if (ret)
1752                 goto error;
1753
1754         /* context entry init */
1755         ret = domain_context_mapping(domain, pdev);
1756         if (!ret)
1757                 return 0;
1758 error:
1759         domain_exit(domain);
1760         return ret;
1761
1762 }
1763
1764 static inline int iommu_prepare_rmrr_dev(struct dmar_rmrr_unit *rmrr,
1765         struct pci_dev *pdev)
1766 {
1767         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
1768                 return 0;
1769         return iommu_prepare_identity_map(pdev, rmrr->base_address,
1770                 rmrr->end_address + 1);
1771 }
1772
1773 #ifdef CONFIG_DMAR_GFX_WA
1774 struct iommu_prepare_data {
1775         struct pci_dev *pdev;
1776         int ret;
1777 };
1778
1779 static int __init iommu_prepare_work_fn(unsigned long start_pfn,
1780                                          unsigned long end_pfn, void *datax)
1781 {
1782         struct iommu_prepare_data *data;
1783
1784         data = (struct iommu_prepare_data *)datax;
1785
1786         data->ret = iommu_prepare_identity_map(data->pdev,
1787                                 start_pfn<<PAGE_SHIFT, end_pfn<<PAGE_SHIFT);
1788         return data->ret;
1789
1790 }
1791
1792 static int __init iommu_prepare_with_active_regions(struct pci_dev *pdev)
1793 {
1794         int nid;
1795         struct iommu_prepare_data data;
1796
1797         data.pdev = pdev;
1798         data.ret = 0;
1799
1800         for_each_online_node(nid) {
1801                 work_with_active_regions(nid, iommu_prepare_work_fn, &data);
1802                 if (data.ret)
1803                         return data.ret;
1804         }
1805         return data.ret;
1806 }
1807
1808 static void __init iommu_prepare_gfx_mapping(void)
1809 {
1810         struct pci_dev *pdev = NULL;
1811         int ret;
1812
1813         for_each_pci_dev(pdev) {
1814                 if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO ||
1815                                 !IS_GFX_DEVICE(pdev))
1816                         continue;
1817                 printk(KERN_INFO "IOMMU: gfx device %s 1-1 mapping\n",
1818                         pci_name(pdev));
1819                 ret = iommu_prepare_with_active_regions(pdev);
1820                 if (ret)
1821                         printk(KERN_ERR "IOMMU: mapping reserved region failed\n");
1822         }
1823 }
1824 #else /* !CONFIG_DMAR_GFX_WA */
1825 static inline void iommu_prepare_gfx_mapping(void)
1826 {
1827         return;
1828 }
1829 #endif
1830
1831 #ifdef CONFIG_DMAR_FLOPPY_WA
1832 static inline void iommu_prepare_isa(void)
1833 {
1834         struct pci_dev *pdev;
1835         int ret;
1836
1837         pdev = pci_get_class(PCI_CLASS_BRIDGE_ISA << 8, NULL);
1838         if (!pdev)
1839                 return;
1840
1841         printk(KERN_INFO "IOMMU: Prepare 0-16M unity mapping for LPC\n");
1842         ret = iommu_prepare_identity_map(pdev, 0, 16*1024*1024);
1843
1844         if (ret)
1845                 printk(KERN_ERR "IOMMU: Failed to create 0-64M identity map, "
1846                         "floppy might not work\n");
1847
1848 }
1849 #else
1850 static inline void iommu_prepare_isa(void)
1851 {
1852         return;
1853 }
1854 #endif /* !CONFIG_DMAR_FLPY_WA */
1855
1856 static int __init init_dmars(void)
1857 {
1858         struct dmar_drhd_unit *drhd;
1859         struct dmar_rmrr_unit *rmrr;
1860         struct pci_dev *pdev;
1861         struct intel_iommu *iommu;
1862         int i, ret;
1863
1864         /*
1865          * for each drhd
1866          *    allocate root
1867          *    initialize and program root entry to not present
1868          * endfor
1869          */
1870         for_each_drhd_unit(drhd) {
1871                 g_num_of_iommus++;
1872                 /*
1873                  * lock not needed as this is only incremented in the single
1874                  * threaded kernel __init code path all other access are read
1875                  * only
1876                  */
1877         }
1878
1879         g_iommus = kcalloc(g_num_of_iommus, sizeof(struct intel_iommu *),
1880                         GFP_KERNEL);
1881         if (!g_iommus) {
1882                 printk(KERN_ERR "Allocating global iommu array failed\n");
1883                 ret = -ENOMEM;
1884                 goto error;
1885         }
1886
1887         deferred_flush = kzalloc(g_num_of_iommus *
1888                 sizeof(struct deferred_flush_tables), GFP_KERNEL);
1889         if (!deferred_flush) {
1890                 kfree(g_iommus);
1891                 ret = -ENOMEM;
1892                 goto error;
1893         }
1894
1895         for_each_drhd_unit(drhd) {
1896                 if (drhd->ignored)
1897                         continue;
1898
1899                 iommu = drhd->iommu;
1900                 g_iommus[iommu->seq_id] = iommu;
1901
1902                 ret = iommu_init_domains(iommu);
1903                 if (ret)
1904                         goto error;
1905
1906                 /*
1907                  * TBD:
1908                  * we could share the same root & context tables
1909                  * amoung all IOMMU's. Need to Split it later.
1910                  */
1911                 ret = iommu_alloc_root_entry(iommu);
1912                 if (ret) {
1913                         printk(KERN_ERR "IOMMU: allocate root entry failed\n");
1914                         goto error;
1915                 }
1916         }
1917
1918         /*
1919          * Start from the sane iommu hardware state.
1920          */
1921         for_each_drhd_unit(drhd) {
1922                 if (drhd->ignored)
1923                         continue;
1924
1925                 iommu = drhd->iommu;
1926
1927                 /*
1928                  * If the queued invalidation is already initialized by us
1929                  * (for example, while enabling interrupt-remapping) then
1930                  * we got the things already rolling from a sane state.
1931                  */
1932                 if (iommu->qi)
1933                         continue;
1934
1935                 /*
1936                  * Clear any previous faults.
1937                  */
1938                 dmar_fault(-1, iommu);
1939                 /*
1940                  * Disable queued invalidation if supported and already enabled
1941                  * before OS handover.
1942                  */
1943                 dmar_disable_qi(iommu);
1944         }
1945
1946         for_each_drhd_unit(drhd) {
1947                 if (drhd->ignored)
1948                         continue;
1949
1950                 iommu = drhd->iommu;
1951
1952                 if (dmar_enable_qi(iommu)) {
1953                         /*
1954                          * Queued Invalidate not enabled, use Register Based
1955                          * Invalidate
1956                          */
1957                         iommu->flush.flush_context = __iommu_flush_context;
1958                         iommu->flush.flush_iotlb = __iommu_flush_iotlb;
1959                         printk(KERN_INFO "IOMMU 0x%Lx: using Register based "
1960                                "invalidation\n",
1961                                (unsigned long long)drhd->reg_base_addr);
1962                 } else {
1963                         iommu->flush.flush_context = qi_flush_context;
1964                         iommu->flush.flush_iotlb = qi_flush_iotlb;
1965                         printk(KERN_INFO "IOMMU 0x%Lx: using Queued "
1966                                "invalidation\n",
1967                                (unsigned long long)drhd->reg_base_addr);
1968                 }
1969         }
1970
1971         /*
1972          * For each rmrr
1973          *   for each dev attached to rmrr
1974          *   do
1975          *     locate drhd for dev, alloc domain for dev
1976          *     allocate free domain
1977          *     allocate page table entries for rmrr
1978          *     if context not allocated for bus
1979          *           allocate and init context
1980          *           set present in root table for this bus
1981          *     init context with domain, translation etc
1982          *    endfor
1983          * endfor
1984          */
1985         for_each_rmrr_units(rmrr) {
1986                 for (i = 0; i < rmrr->devices_cnt; i++) {
1987                         pdev = rmrr->devices[i];
1988                         /* some BIOS lists non-exist devices in DMAR table */
1989                         if (!pdev)
1990                                 continue;
1991                         ret = iommu_prepare_rmrr_dev(rmrr, pdev);
1992                         if (ret)
1993                                 printk(KERN_ERR
1994                                  "IOMMU: mapping reserved region failed\n");
1995                 }
1996         }
1997
1998         iommu_prepare_gfx_mapping();
1999
2000         iommu_prepare_isa();
2001
2002         /*
2003          * for each drhd
2004          *   enable fault log
2005          *   global invalidate context cache
2006          *   global invalidate iotlb
2007          *   enable translation
2008          */
2009         for_each_drhd_unit(drhd) {
2010                 if (drhd->ignored)
2011                         continue;
2012                 iommu = drhd->iommu;
2013
2014                 iommu_flush_write_buffer(iommu);
2015
2016                 ret = dmar_set_interrupt(iommu);
2017                 if (ret)
2018                         goto error;
2019
2020                 iommu_set_root_entry(iommu);
2021
2022                 iommu->flush.flush_context(iommu, 0, 0, 0, DMA_CCMD_GLOBAL_INVL,
2023                                            0);
2024                 iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_GLOBAL_FLUSH,
2025                                          0);
2026                 iommu_disable_protect_mem_regions(iommu);
2027
2028                 ret = iommu_enable_translation(iommu);
2029                 if (ret)
2030                         goto error;
2031         }
2032
2033         return 0;
2034 error:
2035         for_each_drhd_unit(drhd) {
2036                 if (drhd->ignored)
2037                         continue;
2038                 iommu = drhd->iommu;
2039                 free_iommu(iommu);
2040         }
2041         kfree(g_iommus);
2042         return ret;
2043 }
2044
2045 static inline u64 aligned_size(u64 host_addr, size_t size)
2046 {
2047         u64 addr;
2048         addr = (host_addr & (~PAGE_MASK)) + size;
2049         return PAGE_ALIGN(addr);
2050 }
2051
2052 struct iova *
2053 iommu_alloc_iova(struct dmar_domain *domain, size_t size, u64 end)
2054 {
2055         struct iova *piova;
2056
2057         /* Make sure it's in range */
2058         end = min_t(u64, DOMAIN_MAX_ADDR(domain->gaw), end);
2059         if (!size || (IOVA_START_ADDR + size > end))
2060                 return NULL;
2061
2062         piova = alloc_iova(&domain->iovad,
2063                         size >> PAGE_SHIFT, IOVA_PFN(end), 1);
2064         return piova;
2065 }
2066
2067 static struct iova *
2068 __intel_alloc_iova(struct device *dev, struct dmar_domain *domain,
2069                    size_t size, u64 dma_mask)
2070 {
2071         struct pci_dev *pdev = to_pci_dev(dev);
2072         struct iova *iova = NULL;
2073
2074         if (dma_mask <= DMA_BIT_MASK(32) || dmar_forcedac)
2075                 iova = iommu_alloc_iova(domain, size, dma_mask);
2076         else {
2077                 /*
2078                  * First try to allocate an io virtual address in
2079                  * DMA_BIT_MASK(32) and if that fails then try allocating
2080                  * from higher range
2081                  */
2082                 iova = iommu_alloc_iova(domain, size, DMA_BIT_MASK(32));
2083                 if (!iova)
2084                         iova = iommu_alloc_iova(domain, size, dma_mask);
2085         }
2086
2087         if (!iova) {
2088                 printk(KERN_ERR"Allocating iova for %s failed", pci_name(pdev));
2089                 return NULL;
2090         }
2091
2092         return iova;
2093 }
2094
2095 static struct dmar_domain *
2096 get_valid_domain_for_dev(struct pci_dev *pdev)
2097 {
2098         struct dmar_domain *domain;
2099         int ret;
2100
2101         domain = get_domain_for_dev(pdev,
2102                         DEFAULT_DOMAIN_ADDRESS_WIDTH);
2103         if (!domain) {
2104                 printk(KERN_ERR
2105                         "Allocating domain for %s failed", pci_name(pdev));
2106                 return NULL;
2107         }
2108
2109         /* make sure context mapping is ok */
2110         if (unlikely(!domain_context_mapped(pdev))) {
2111                 ret = domain_context_mapping(domain, pdev);
2112                 if (ret) {
2113                         printk(KERN_ERR
2114                                 "Domain context map for %s failed",
2115                                 pci_name(pdev));
2116                         return NULL;
2117                 }
2118         }
2119
2120         return domain;
2121 }
2122
2123 static dma_addr_t __intel_map_single(struct device *hwdev, phys_addr_t paddr,
2124                                      size_t size, int dir, u64 dma_mask)
2125 {
2126         struct pci_dev *pdev = to_pci_dev(hwdev);
2127         struct dmar_domain *domain;
2128         phys_addr_t start_paddr;
2129         struct iova *iova;
2130         int prot = 0;
2131         int ret;
2132         struct intel_iommu *iommu;
2133
2134         BUG_ON(dir == DMA_NONE);
2135         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2136                 return paddr;
2137
2138         domain = get_valid_domain_for_dev(pdev);
2139         if (!domain)
2140                 return 0;
2141
2142         iommu = domain_get_iommu(domain);
2143         size = aligned_size((u64)paddr, size);
2144
2145         iova = __intel_alloc_iova(hwdev, domain, size, pdev->dma_mask);
2146         if (!iova)
2147                 goto error;
2148
2149         start_paddr = (phys_addr_t)iova->pfn_lo << PAGE_SHIFT;
2150
2151         /*
2152          * Check if DMAR supports zero-length reads on write only
2153          * mappings..
2154          */
2155         if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
2156                         !cap_zlr(iommu->cap))
2157                 prot |= DMA_PTE_READ;
2158         if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
2159                 prot |= DMA_PTE_WRITE;
2160         /*
2161          * paddr - (paddr + size) might be partial page, we should map the whole
2162          * page.  Note: if two part of one page are separately mapped, we
2163          * might have two guest_addr mapping to the same host paddr, but this
2164          * is not a big problem
2165          */
2166         ret = domain_page_mapping(domain, start_paddr,
2167                 ((u64)paddr) & PAGE_MASK, size, prot);
2168         if (ret)
2169                 goto error;
2170
2171         /* it's a non-present to present mapping */
2172         ret = iommu_flush_iotlb_psi(iommu, domain->id,
2173                         start_paddr, size >> VTD_PAGE_SHIFT, 1);
2174         if (ret)
2175                 iommu_flush_write_buffer(iommu);
2176
2177         return start_paddr + ((u64)paddr & (~PAGE_MASK));
2178
2179 error:
2180         if (iova)
2181                 __free_iova(&domain->iovad, iova);
2182         printk(KERN_ERR"Device %s request: %zx@%llx dir %d --- failed\n",
2183                 pci_name(pdev), size, (unsigned long long)paddr, dir);
2184         return 0;
2185 }
2186
2187 static dma_addr_t intel_map_page(struct device *dev, struct page *page,
2188                                  unsigned long offset, size_t size,
2189                                  enum dma_data_direction dir,
2190                                  struct dma_attrs *attrs)
2191 {
2192         return __intel_map_single(dev, page_to_phys(page) + offset, size,
2193                                   dir, to_pci_dev(dev)->dma_mask);
2194 }
2195
2196 static void flush_unmaps(void)
2197 {
2198         int i, j;
2199
2200         timer_on = 0;
2201
2202         /* just flush them all */
2203         for (i = 0; i < g_num_of_iommus; i++) {
2204                 struct intel_iommu *iommu = g_iommus[i];
2205                 if (!iommu)
2206                         continue;
2207
2208                 if (deferred_flush[i].next) {
2209                         iommu->flush.flush_iotlb(iommu, 0, 0, 0,
2210                                                  DMA_TLB_GLOBAL_FLUSH, 0);
2211                         for (j = 0; j < deferred_flush[i].next; j++) {
2212                                 __free_iova(&deferred_flush[i].domain[j]->iovad,
2213                                                 deferred_flush[i].iova[j]);
2214                         }
2215                         deferred_flush[i].next = 0;
2216                 }
2217         }
2218
2219         list_size = 0;
2220 }
2221
2222 static void flush_unmaps_timeout(unsigned long data)
2223 {
2224         unsigned long flags;
2225
2226         spin_lock_irqsave(&async_umap_flush_lock, flags);
2227         flush_unmaps();
2228         spin_unlock_irqrestore(&async_umap_flush_lock, flags);
2229 }
2230
2231 static void add_unmap(struct dmar_domain *dom, struct iova *iova)
2232 {
2233         unsigned long flags;
2234         int next, iommu_id;
2235         struct intel_iommu *iommu;
2236
2237         spin_lock_irqsave(&async_umap_flush_lock, flags);
2238         if (list_size == HIGH_WATER_MARK)
2239                 flush_unmaps();
2240
2241         iommu = domain_get_iommu(dom);
2242         iommu_id = iommu->seq_id;
2243
2244         next = deferred_flush[iommu_id].next;
2245         deferred_flush[iommu_id].domain[next] = dom;
2246         deferred_flush[iommu_id].iova[next] = iova;
2247         deferred_flush[iommu_id].next++;
2248
2249         if (!timer_on) {
2250                 mod_timer(&unmap_timer, jiffies + msecs_to_jiffies(10));
2251                 timer_on = 1;
2252         }
2253         list_size++;
2254         spin_unlock_irqrestore(&async_umap_flush_lock, flags);
2255 }
2256
2257 static void intel_unmap_page(struct device *dev, dma_addr_t dev_addr,
2258                              size_t size, enum dma_data_direction dir,
2259                              struct dma_attrs *attrs)
2260 {
2261         struct pci_dev *pdev = to_pci_dev(dev);
2262         struct dmar_domain *domain;
2263         unsigned long start_addr;
2264         struct iova *iova;
2265         struct intel_iommu *iommu;
2266
2267         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2268                 return;
2269         domain = find_domain(pdev);
2270         BUG_ON(!domain);
2271
2272         iommu = domain_get_iommu(domain);
2273
2274         iova = find_iova(&domain->iovad, IOVA_PFN(dev_addr));
2275         if (!iova)
2276                 return;
2277
2278         start_addr = iova->pfn_lo << PAGE_SHIFT;
2279         size = aligned_size((u64)dev_addr, size);
2280
2281         pr_debug("Device %s unmapping: %zx@%llx\n",
2282                 pci_name(pdev), size, (unsigned long long)start_addr);
2283
2284         /*  clear the whole page */
2285         dma_pte_clear_range(domain, start_addr, start_addr + size);
2286         /* free page tables */
2287         dma_pte_free_pagetable(domain, start_addr, start_addr + size);
2288         if (intel_iommu_strict) {
2289                 if (iommu_flush_iotlb_psi(iommu,
2290                         domain->id, start_addr, size >> VTD_PAGE_SHIFT, 0))
2291                         iommu_flush_write_buffer(iommu);
2292                 /* free iova */
2293                 __free_iova(&domain->iovad, iova);
2294         } else {
2295                 add_unmap(domain, iova);
2296                 /*
2297                  * queue up the release of the unmap to save the 1/6th of the
2298                  * cpu used up by the iotlb flush operation...
2299                  */
2300         }
2301 }
2302
2303 static void intel_unmap_single(struct device *dev, dma_addr_t dev_addr, size_t size,
2304                                int dir)
2305 {
2306         intel_unmap_page(dev, dev_addr, size, dir, NULL);
2307 }
2308
2309 static void *intel_alloc_coherent(struct device *hwdev, size_t size,
2310                                   dma_addr_t *dma_handle, gfp_t flags)
2311 {
2312         void *vaddr;
2313         int order;
2314
2315         size = PAGE_ALIGN(size);
2316         order = get_order(size);
2317         flags &= ~(GFP_DMA | GFP_DMA32);
2318
2319         vaddr = (void *)__get_free_pages(flags, order);
2320         if (!vaddr)
2321                 return NULL;
2322         memset(vaddr, 0, size);
2323
2324         *dma_handle = __intel_map_single(hwdev, virt_to_bus(vaddr), size,
2325                                          DMA_BIDIRECTIONAL,
2326                                          hwdev->coherent_dma_mask);
2327         if (*dma_handle)
2328                 return vaddr;
2329         free_pages((unsigned long)vaddr, order);
2330         return NULL;
2331 }
2332
2333 static void intel_free_coherent(struct device *hwdev, size_t size, void *vaddr,
2334                                 dma_addr_t dma_handle)
2335 {
2336         int order;
2337
2338         size = PAGE_ALIGN(size);
2339         order = get_order(size);
2340
2341         intel_unmap_single(hwdev, dma_handle, size, DMA_BIDIRECTIONAL);
2342         free_pages((unsigned long)vaddr, order);
2343 }
2344
2345 static void intel_unmap_sg(struct device *hwdev, struct scatterlist *sglist,
2346                            int nelems, enum dma_data_direction dir,
2347                            struct dma_attrs *attrs)
2348 {
2349         int i;
2350         struct pci_dev *pdev = to_pci_dev(hwdev);
2351         struct dmar_domain *domain;
2352         unsigned long start_addr;
2353         struct iova *iova;
2354         size_t size = 0;
2355         phys_addr_t addr;
2356         struct scatterlist *sg;
2357         struct intel_iommu *iommu;
2358
2359         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2360                 return;
2361
2362         domain = find_domain(pdev);
2363         BUG_ON(!domain);
2364
2365         iommu = domain_get_iommu(domain);
2366
2367         iova = find_iova(&domain->iovad, IOVA_PFN(sglist[0].dma_address));
2368         if (!iova)
2369                 return;
2370         for_each_sg(sglist, sg, nelems, i) {
2371                 addr = page_to_phys(sg_page(sg)) + sg->offset;
2372                 size += aligned_size((u64)addr, sg->length);
2373         }
2374
2375         start_addr = iova->pfn_lo << PAGE_SHIFT;
2376
2377         /*  clear the whole page */
2378         dma_pte_clear_range(domain, start_addr, start_addr + size);
2379         /* free page tables */
2380         dma_pte_free_pagetable(domain, start_addr, start_addr + size);
2381
2382         if (iommu_flush_iotlb_psi(iommu, domain->id, start_addr,
2383                         size >> VTD_PAGE_SHIFT, 0))
2384                 iommu_flush_write_buffer(iommu);
2385
2386         /* free iova */
2387         __free_iova(&domain->iovad, iova);
2388 }
2389
2390 static int intel_nontranslate_map_sg(struct device *hddev,
2391         struct scatterlist *sglist, int nelems, int dir)
2392 {
2393         int i;
2394         struct scatterlist *sg;
2395
2396         for_each_sg(sglist, sg, nelems, i) {
2397                 BUG_ON(!sg_page(sg));
2398                 sg->dma_address = page_to_phys(sg_page(sg)) + sg->offset;
2399                 sg->dma_length = sg->length;
2400         }
2401         return nelems;
2402 }
2403
2404 static int intel_map_sg(struct device *hwdev, struct scatterlist *sglist, int nelems,
2405                         enum dma_data_direction dir, struct dma_attrs *attrs)
2406 {
2407         phys_addr_t addr;
2408         int i;
2409         struct pci_dev *pdev = to_pci_dev(hwdev);
2410         struct dmar_domain *domain;
2411         size_t size = 0;
2412         int prot = 0;
2413         size_t offset = 0;
2414         struct iova *iova = NULL;
2415         int ret;
2416         struct scatterlist *sg;
2417         unsigned long start_addr;
2418         struct intel_iommu *iommu;
2419
2420         BUG_ON(dir == DMA_NONE);
2421         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2422                 return intel_nontranslate_map_sg(hwdev, sglist, nelems, dir);
2423
2424         domain = get_valid_domain_for_dev(pdev);
2425         if (!domain)
2426                 return 0;
2427
2428         iommu = domain_get_iommu(domain);
2429
2430         for_each_sg(sglist, sg, nelems, i) {
2431                 addr = page_to_phys(sg_page(sg)) + sg->offset;
2432                 size += aligned_size((u64)addr, sg->length);
2433         }
2434
2435         iova = __intel_alloc_iova(hwdev, domain, size, pdev->dma_mask);
2436         if (!iova) {
2437                 sglist->dma_length = 0;
2438                 return 0;
2439         }
2440
2441         /*
2442          * Check if DMAR supports zero-length reads on write only
2443          * mappings..
2444          */
2445         if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
2446                         !cap_zlr(iommu->cap))
2447                 prot |= DMA_PTE_READ;
2448         if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
2449                 prot |= DMA_PTE_WRITE;
2450
2451         start_addr = iova->pfn_lo << PAGE_SHIFT;
2452         offset = 0;
2453         for_each_sg(sglist, sg, nelems, i) {
2454                 addr = page_to_phys(sg_page(sg)) + sg->offset;
2455                 size = aligned_size((u64)addr, sg->length);
2456                 ret = domain_page_mapping(domain, start_addr + offset,
2457                         ((u64)addr) & PAGE_MASK,
2458                         size, prot);
2459                 if (ret) {
2460                         /*  clear the page */
2461                         dma_pte_clear_range(domain, start_addr,
2462                                   start_addr + offset);
2463                         /* free page tables */
2464                         dma_pte_free_pagetable(domain, start_addr,
2465                                   start_addr + offset);
2466                         /* free iova */
2467                         __free_iova(&domain->iovad, iova);
2468                         return 0;
2469                 }
2470                 sg->dma_address = start_addr + offset +
2471                                 ((u64)addr & (~PAGE_MASK));
2472                 sg->dma_length = sg->length;
2473                 offset += size;
2474         }
2475
2476         /* it's a non-present to present mapping */
2477         if (iommu_flush_iotlb_psi(iommu, domain->id,
2478                         start_addr, offset >> VTD_PAGE_SHIFT, 1))
2479                 iommu_flush_write_buffer(iommu);
2480         return nelems;
2481 }
2482
2483 static int intel_mapping_error(struct device *dev, dma_addr_t dma_addr)
2484 {
2485         return !dma_addr;
2486 }
2487
2488 struct dma_map_ops intel_dma_ops = {
2489         .alloc_coherent = intel_alloc_coherent,
2490         .free_coherent = intel_free_coherent,
2491         .map_sg = intel_map_sg,
2492         .unmap_sg = intel_unmap_sg,
2493         .map_page = intel_map_page,
2494         .unmap_page = intel_unmap_page,
2495         .mapping_error = intel_mapping_error,
2496 };
2497
2498 static inline int iommu_domain_cache_init(void)
2499 {
2500         int ret = 0;
2501
2502         iommu_domain_cache = kmem_cache_create("iommu_domain",
2503                                          sizeof(struct dmar_domain),
2504                                          0,
2505                                          SLAB_HWCACHE_ALIGN,
2506
2507                                          NULL);
2508         if (!iommu_domain_cache) {
2509                 printk(KERN_ERR "Couldn't create iommu_domain cache\n");
2510                 ret = -ENOMEM;
2511         }
2512
2513         return ret;
2514 }
2515
2516 static inline int iommu_devinfo_cache_init(void)
2517 {
2518         int ret = 0;
2519
2520         iommu_devinfo_cache = kmem_cache_create("iommu_devinfo",
2521                                          sizeof(struct device_domain_info),
2522                                          0,
2523                                          SLAB_HWCACHE_ALIGN,
2524                                          NULL);
2525         if (!iommu_devinfo_cache) {
2526                 printk(KERN_ERR "Couldn't create devinfo cache\n");
2527                 ret = -ENOMEM;
2528         }
2529
2530         return ret;
2531 }
2532
2533 static inline int iommu_iova_cache_init(void)
2534 {
2535         int ret = 0;
2536
2537         iommu_iova_cache = kmem_cache_create("iommu_iova",
2538                                          sizeof(struct iova),
2539                                          0,
2540                                          SLAB_HWCACHE_ALIGN,
2541                                          NULL);
2542         if (!iommu_iova_cache) {
2543                 printk(KERN_ERR "Couldn't create iova cache\n");
2544                 ret = -ENOMEM;
2545         }
2546
2547         return ret;
2548 }
2549
2550 static int __init iommu_init_mempool(void)
2551 {
2552         int ret;
2553         ret = iommu_iova_cache_init();
2554         if (ret)
2555                 return ret;
2556
2557         ret = iommu_domain_cache_init();
2558         if (ret)
2559                 goto domain_error;
2560
2561         ret = iommu_devinfo_cache_init();
2562         if (!ret)
2563                 return ret;
2564
2565         kmem_cache_destroy(iommu_domain_cache);
2566 domain_error:
2567         kmem_cache_destroy(iommu_iova_cache);
2568
2569         return -ENOMEM;
2570 }
2571
2572 static void __init iommu_exit_mempool(void)
2573 {
2574         kmem_cache_destroy(iommu_devinfo_cache);
2575         kmem_cache_destroy(iommu_domain_cache);
2576         kmem_cache_destroy(iommu_iova_cache);
2577
2578 }
2579
2580 static void __init init_no_remapping_devices(void)
2581 {
2582         struct dmar_drhd_unit *drhd;
2583
2584         for_each_drhd_unit(drhd) {
2585                 if (!drhd->include_all) {
2586                         int i;
2587                         for (i = 0; i < drhd->devices_cnt; i++)
2588                                 if (drhd->devices[i] != NULL)
2589                                         break;
2590                         /* ignore DMAR unit if no pci devices exist */
2591                         if (i == drhd->devices_cnt)
2592                                 drhd->ignored = 1;
2593                 }
2594         }
2595
2596         if (dmar_map_gfx)
2597                 return;
2598
2599         for_each_drhd_unit(drhd) {
2600                 int i;
2601                 if (drhd->ignored || drhd->include_all)
2602                         continue;
2603
2604                 for (i = 0; i < drhd->devices_cnt; i++)
2605                         if (drhd->devices[i] &&
2606                                 !IS_GFX_DEVICE(drhd->devices[i]))
2607                                 break;
2608
2609                 if (i < drhd->devices_cnt)
2610                         continue;
2611
2612                 /* bypass IOMMU if it is just for gfx devices */
2613                 drhd->ignored = 1;
2614                 for (i = 0; i < drhd->devices_cnt; i++) {
2615                         if (!drhd->devices[i])
2616                                 continue;
2617                         drhd->devices[i]->dev.archdata.iommu = DUMMY_DEVICE_DOMAIN_INFO;
2618                 }
2619         }
2620 }
2621
2622 #ifdef CONFIG_SUSPEND
2623 static int init_iommu_hw(void)
2624 {
2625         struct dmar_drhd_unit *drhd;
2626         struct intel_iommu *iommu = NULL;
2627
2628         for_each_active_iommu(iommu, drhd)
2629                 if (iommu->qi)
2630                         dmar_reenable_qi(iommu);
2631
2632         for_each_active_iommu(iommu, drhd) {
2633                 iommu_flush_write_buffer(iommu);
2634
2635                 iommu_set_root_entry(iommu);
2636
2637                 iommu->flush.flush_context(iommu, 0, 0, 0,
2638                                                 DMA_CCMD_GLOBAL_INVL, 0);
2639                 iommu->flush.flush_iotlb(iommu, 0, 0, 0,
2640                                                 DMA_TLB_GLOBAL_FLUSH, 0);
2641                 iommu_disable_protect_mem_regions(iommu);
2642                 iommu_enable_translation(iommu);
2643         }
2644
2645         return 0;
2646 }
2647
2648 static void iommu_flush_all(void)
2649 {
2650         struct dmar_drhd_unit *drhd;
2651         struct intel_iommu *iommu;
2652
2653         for_each_active_iommu(iommu, drhd) {
2654                 iommu->flush.flush_context(iommu, 0, 0, 0,
2655                                                 DMA_CCMD_GLOBAL_INVL, 0);
2656                 iommu->flush.flush_iotlb(iommu, 0, 0, 0,
2657                                                 DMA_TLB_GLOBAL_FLUSH, 0);
2658         }
2659 }
2660
2661 static int iommu_suspend(struct sys_device *dev, pm_message_t state)
2662 {
2663         struct dmar_drhd_unit *drhd;
2664         struct intel_iommu *iommu = NULL;
2665         unsigned long flag;
2666
2667         for_each_active_iommu(iommu, drhd) {
2668                 iommu->iommu_state = kzalloc(sizeof(u32) * MAX_SR_DMAR_REGS,
2669                                                  GFP_ATOMIC);
2670                 if (!iommu->iommu_state)
2671                         goto nomem;
2672         }
2673
2674         iommu_flush_all();
2675
2676         for_each_active_iommu(iommu, drhd) {
2677                 iommu_disable_translation(iommu);
2678
2679                 spin_lock_irqsave(&iommu->register_lock, flag);
2680
2681                 iommu->iommu_state[SR_DMAR_FECTL_REG] =
2682                         readl(iommu->reg + DMAR_FECTL_REG);
2683                 iommu->iommu_state[SR_DMAR_FEDATA_REG] =
2684                         readl(iommu->reg + DMAR_FEDATA_REG);
2685                 iommu->iommu_state[SR_DMAR_FEADDR_REG] =
2686                         readl(iommu->reg + DMAR_FEADDR_REG);
2687                 iommu->iommu_state[SR_DMAR_FEUADDR_REG] =
2688                         readl(iommu->reg + DMAR_FEUADDR_REG);
2689
2690                 spin_unlock_irqrestore(&iommu->register_lock, flag);
2691         }
2692         return 0;
2693
2694 nomem:
2695         for_each_active_iommu(iommu, drhd)
2696                 kfree(iommu->iommu_state);
2697
2698         return -ENOMEM;
2699 }
2700
2701 static int iommu_resume(struct sys_device *dev)
2702 {
2703         struct dmar_drhd_unit *drhd;
2704         struct intel_iommu *iommu = NULL;
2705         unsigned long flag;
2706
2707         if (init_iommu_hw()) {
2708                 WARN(1, "IOMMU setup failed, DMAR can not resume!\n");
2709                 return -EIO;
2710         }
2711
2712         for_each_active_iommu(iommu, drhd) {
2713
2714                 spin_lock_irqsave(&iommu->register_lock, flag);
2715
2716                 writel(iommu->iommu_state[SR_DMAR_FECTL_REG],
2717                         iommu->reg + DMAR_FECTL_REG);
2718                 writel(iommu->iommu_state[SR_DMAR_FEDATA_REG],
2719                         iommu->reg + DMAR_FEDATA_REG);
2720                 writel(iommu->iommu_state[SR_DMAR_FEADDR_REG],
2721                         iommu->reg + DMAR_FEADDR_REG);
2722                 writel(iommu->iommu_state[SR_DMAR_FEUADDR_REG],
2723                         iommu->reg + DMAR_FEUADDR_REG);
2724
2725                 spin_unlock_irqrestore(&iommu->register_lock, flag);
2726         }
2727
2728         for_each_active_iommu(iommu, drhd)
2729                 kfree(iommu->iommu_state);
2730
2731         return 0;
2732 }
2733
2734 static struct sysdev_class iommu_sysclass = {
2735         .name           = "iommu",
2736         .resume         = iommu_resume,
2737         .suspend        = iommu_suspend,
2738 };
2739
2740 static struct sys_device device_iommu = {
2741         .cls    = &iommu_sysclass,
2742 };
2743
2744 static int __init init_iommu_sysfs(void)
2745 {
2746         int error;
2747
2748         error = sysdev_class_register(&iommu_sysclass);
2749         if (error)
2750                 return error;
2751
2752         error = sysdev_register(&device_iommu);
2753         if (error)
2754                 sysdev_class_unregister(&iommu_sysclass);
2755
2756         return error;
2757 }
2758
2759 #else
2760 static int __init init_iommu_sysfs(void)
2761 {
2762         return 0;
2763 }
2764 #endif  /* CONFIG_PM */
2765
2766 int __init intel_iommu_init(void)
2767 {
2768         int ret = 0;
2769
2770         if (dmar_table_init())
2771                 return  -ENODEV;
2772
2773         if (dmar_dev_scope_init())
2774                 return  -ENODEV;
2775
2776         /*
2777          * Check the need for DMA-remapping initialization now.
2778          * Above initialization will also be used by Interrupt-remapping.
2779          */
2780         if (no_iommu || swiotlb || dmar_disabled)
2781                 return -ENODEV;
2782
2783         iommu_init_mempool();
2784         dmar_init_reserved_ranges();
2785
2786         init_no_remapping_devices();
2787
2788         ret = init_dmars();
2789         if (ret) {
2790                 printk(KERN_ERR "IOMMU: dmar init failed\n");
2791                 put_iova_domain(&reserved_iova_list);
2792                 iommu_exit_mempool();
2793                 return ret;
2794         }
2795         printk(KERN_INFO
2796         "PCI-DMA: Intel(R) Virtualization Technology for Directed I/O\n");
2797
2798         init_timer(&unmap_timer);
2799         force_iommu = 1;
2800         dma_ops = &intel_dma_ops;
2801         init_iommu_sysfs();
2802
2803         register_iommu(&intel_iommu_ops);
2804
2805         return 0;
2806 }
2807
2808 static int vm_domain_add_dev_info(struct dmar_domain *domain,
2809                                   struct pci_dev *pdev)
2810 {
2811         struct device_domain_info *info;
2812         unsigned long flags;
2813
2814         info = alloc_devinfo_mem();
2815         if (!info)
2816                 return -ENOMEM;
2817
2818         info->segment = pci_domain_nr(pdev->bus);
2819         info->bus = pdev->bus->number;
2820         info->devfn = pdev->devfn;
2821         info->dev = pdev;
2822         info->domain = domain;
2823
2824         spin_lock_irqsave(&device_domain_lock, flags);
2825         list_add(&info->link, &domain->devices);
2826         list_add(&info->global, &device_domain_list);
2827         pdev->dev.archdata.iommu = info;
2828         spin_unlock_irqrestore(&device_domain_lock, flags);
2829
2830         return 0;
2831 }
2832
2833 static void iommu_detach_dependent_devices(struct intel_iommu *iommu,
2834                                            struct pci_dev *pdev)
2835 {
2836         struct pci_dev *tmp, *parent;
2837
2838         if (!iommu || !pdev)
2839                 return;
2840
2841         /* dependent device detach */
2842         tmp = pci_find_upstream_pcie_bridge(pdev);
2843         /* Secondary interface's bus number and devfn 0 */
2844         if (tmp) {
2845                 parent = pdev->bus->self;
2846                 while (parent != tmp) {
2847                         iommu_detach_dev(iommu, parent->bus->number,
2848                                          parent->devfn);
2849                         parent = parent->bus->self;
2850                 }
2851                 if (tmp->is_pcie) /* this is a PCIE-to-PCI bridge */
2852                         iommu_detach_dev(iommu,
2853                                 tmp->subordinate->number, 0);
2854                 else /* this is a legacy PCI bridge */
2855                         iommu_detach_dev(iommu, tmp->bus->number,
2856                                          tmp->devfn);
2857         }
2858 }
2859
2860 static void vm_domain_remove_one_dev_info(struct dmar_domain *domain,
2861                                           struct pci_dev *pdev)
2862 {
2863         struct device_domain_info *info;
2864         struct intel_iommu *iommu;
2865         unsigned long flags;
2866         int found = 0;
2867         struct list_head *entry, *tmp;
2868
2869         iommu = device_to_iommu(pci_domain_nr(pdev->bus), pdev->bus->number,
2870                                 pdev->devfn);
2871         if (!iommu)
2872                 return;
2873
2874         spin_lock_irqsave(&device_domain_lock, flags);
2875         list_for_each_safe(entry, tmp, &domain->devices) {
2876                 info = list_entry(entry, struct device_domain_info, link);
2877                 /* No need to compare PCI domain; it has to be the same */
2878                 if (info->bus == pdev->bus->number &&
2879                     info->devfn == pdev->devfn) {
2880                         list_del(&info->link);
2881                         list_del(&info->global);
2882                         if (info->dev)
2883                                 info->dev->dev.archdata.iommu = NULL;
2884                         spin_unlock_irqrestore(&device_domain_lock, flags);
2885
2886                         iommu_detach_dev(iommu, info->bus, info->devfn);
2887                         iommu_detach_dependent_devices(iommu, pdev);
2888                         free_devinfo_mem(info);
2889
2890                         spin_lock_irqsave(&device_domain_lock, flags);
2891
2892                         if (found)
2893                                 break;
2894                         else
2895                                 continue;
2896                 }
2897
2898                 /* if there is no other devices under the same iommu
2899                  * owned by this domain, clear this iommu in iommu_bmp
2900                  * update iommu count and coherency
2901                  */
2902                 if (iommu == device_to_iommu(info->segment, info->bus,
2903                                             info->devfn))
2904                         found = 1;
2905         }
2906
2907         if (found == 0) {
2908                 unsigned long tmp_flags;
2909                 spin_lock_irqsave(&domain->iommu_lock, tmp_flags);
2910                 clear_bit(iommu->seq_id, &domain->iommu_bmp);
2911                 domain->iommu_count--;
2912                 domain_update_iommu_cap(domain);
2913                 spin_unlock_irqrestore(&domain->iommu_lock, tmp_flags);
2914         }
2915
2916         spin_unlock_irqrestore(&device_domain_lock, flags);
2917 }
2918
2919 static void vm_domain_remove_all_dev_info(struct dmar_domain *domain)
2920 {
2921         struct device_domain_info *info;
2922         struct intel_iommu *iommu;
2923         unsigned long flags1, flags2;
2924
2925         spin_lock_irqsave(&device_domain_lock, flags1);
2926         while (!list_empty(&domain->devices)) {
2927                 info = list_entry(domain->devices.next,
2928                         struct device_domain_info, link);
2929                 list_del(&info->link);
2930                 list_del(&info->global);
2931                 if (info->dev)
2932                         info->dev->dev.archdata.iommu = NULL;
2933
2934                 spin_unlock_irqrestore(&device_domain_lock, flags1);
2935
2936                 iommu = device_to_iommu(info->segment, info->bus, info->devfn);
2937                 iommu_detach_dev(iommu, info->bus, info->devfn);
2938                 iommu_detach_dependent_devices(iommu, info->dev);
2939
2940                 /* clear this iommu in iommu_bmp, update iommu count
2941                  * and capabilities
2942                  */
2943                 spin_lock_irqsave(&domain->iommu_lock, flags2);
2944                 if (test_and_clear_bit(iommu->seq_id,
2945                                        &domain->iommu_bmp)) {
2946                         domain->iommu_count--;
2947                         domain_update_iommu_cap(domain);
2948                 }
2949                 spin_unlock_irqrestore(&domain->iommu_lock, flags2);
2950
2951                 free_devinfo_mem(info);
2952                 spin_lock_irqsave(&device_domain_lock, flags1);
2953         }
2954         spin_unlock_irqrestore(&device_domain_lock, flags1);
2955 }
2956
2957 /* domain id for virtual machine, it won't be set in context */
2958 static unsigned long vm_domid;
2959
2960 static int vm_domain_min_agaw(struct dmar_domain *domain)
2961 {
2962         int i;
2963         int min_agaw = domain->agaw;
2964
2965         i = find_first_bit(&domain->iommu_bmp, g_num_of_iommus);
2966         for (; i < g_num_of_iommus; ) {
2967                 if (min_agaw > g_iommus[i]->agaw)
2968                         min_agaw = g_iommus[i]->agaw;
2969
2970                 i = find_next_bit(&domain->iommu_bmp, g_num_of_iommus, i+1);
2971         }
2972
2973         return min_agaw;
2974 }
2975
2976 static struct dmar_domain *iommu_alloc_vm_domain(void)
2977 {
2978         struct dmar_domain *domain;
2979
2980         domain = alloc_domain_mem();
2981         if (!domain)
2982                 return NULL;
2983
2984         domain->id = vm_domid++;
2985         memset(&domain->iommu_bmp, 0, sizeof(unsigned long));
2986         domain->flags = DOMAIN_FLAG_VIRTUAL_MACHINE;
2987
2988         return domain;
2989 }
2990
2991 static int vm_domain_init(struct dmar_domain *domain, int guest_width)
2992 {
2993         int adjust_width;
2994
2995         init_iova_domain(&domain->iovad, DMA_32BIT_PFN);
2996         spin_lock_init(&domain->mapping_lock);
2997         spin_lock_init(&domain->iommu_lock);
2998
2999         domain_reserve_special_ranges(domain);
3000
3001         /* calculate AGAW */
3002         domain->gaw = guest_width;
3003         adjust_width = guestwidth_to_adjustwidth(guest_width);
3004         domain->agaw = width_to_agaw(adjust_width);
3005
3006         INIT_LIST_HEAD(&domain->devices);
3007
3008         domain->iommu_count = 0;
3009         domain->iommu_coherency = 0;
3010         domain->max_addr = 0;
3011
3012         /* always allocate the top pgd */
3013         domain->pgd = (struct dma_pte *)alloc_pgtable_page();
3014         if (!domain->pgd)
3015                 return -ENOMEM;
3016         domain_flush_cache(domain, domain->pgd, PAGE_SIZE);
3017         return 0;
3018 }
3019
3020 static void iommu_free_vm_domain(struct dmar_domain *domain)
3021 {
3022         unsigned long flags;
3023         struct dmar_drhd_unit *drhd;
3024         struct intel_iommu *iommu;
3025         unsigned long i;
3026         unsigned long ndomains;
3027
3028         for_each_drhd_unit(drhd) {
3029                 if (drhd->ignored)
3030                         continue;
3031                 iommu = drhd->iommu;
3032
3033                 ndomains = cap_ndoms(iommu->cap);
3034                 i = find_first_bit(iommu->domain_ids, ndomains);
3035                 for (; i < ndomains; ) {
3036                         if (iommu->domains[i] == domain) {
3037                                 spin_lock_irqsave(&iommu->lock, flags);
3038                                 clear_bit(i, iommu->domain_ids);
3039                                 iommu->domains[i] = NULL;
3040                                 spin_unlock_irqrestore(&iommu->lock, flags);
3041                                 break;
3042                         }
3043                         i = find_next_bit(iommu->domain_ids, ndomains, i+1);
3044                 }
3045         }
3046 }
3047
3048 static void vm_domain_exit(struct dmar_domain *domain)
3049 {
3050         u64 end;
3051
3052         /* Domain 0 is reserved, so dont process it */
3053         if (!domain)
3054                 return;
3055
3056         vm_domain_remove_all_dev_info(domain);
3057         /* destroy iovas */
3058         put_iova_domain(&domain->iovad);
3059         end = DOMAIN_MAX_ADDR(domain->gaw);
3060         end = end & (~VTD_PAGE_MASK);
3061
3062         /* clear ptes */
3063         dma_pte_clear_range(domain, 0, end);
3064
3065         /* free page tables */
3066         dma_pte_free_pagetable(domain, 0, end);
3067
3068         iommu_free_vm_domain(domain);
3069         free_domain_mem(domain);
3070 }
3071
3072 static int intel_iommu_domain_init(struct iommu_domain *domain)
3073 {
3074         struct dmar_domain *dmar_domain;
3075
3076         dmar_domain = iommu_alloc_vm_domain();
3077         if (!dmar_domain) {
3078                 printk(KERN_ERR
3079                         "intel_iommu_domain_init: dmar_domain == NULL\n");
3080                 return -ENOMEM;
3081         }
3082         if (vm_domain_init(dmar_domain, DEFAULT_DOMAIN_ADDRESS_WIDTH)) {
3083                 printk(KERN_ERR
3084                         "intel_iommu_domain_init() failed\n");
3085                 vm_domain_exit(dmar_domain);
3086                 return -ENOMEM;
3087         }
3088         domain->priv = dmar_domain;
3089
3090         return 0;
3091 }
3092
3093 static void intel_iommu_domain_destroy(struct iommu_domain *domain)
3094 {
3095         struct dmar_domain *dmar_domain = domain->priv;
3096
3097         domain->priv = NULL;
3098         vm_domain_exit(dmar_domain);
3099 }
3100
3101 static int intel_iommu_attach_device(struct iommu_domain *domain,
3102                                      struct device *dev)
3103 {
3104         struct dmar_domain *dmar_domain = domain->priv;
3105         struct pci_dev *pdev = to_pci_dev(dev);
3106         struct intel_iommu *iommu;
3107         int addr_width;
3108         u64 end;
3109         int ret;
3110
3111         /* normally pdev is not mapped */
3112         if (unlikely(domain_context_mapped(pdev))) {
3113                 struct dmar_domain *old_domain;
3114
3115                 old_domain = find_domain(pdev);
3116                 if (old_domain) {
3117                         if (dmar_domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE)
3118                                 vm_domain_remove_one_dev_info(old_domain, pdev);
3119                         else
3120                                 domain_remove_dev_info(old_domain);
3121                 }
3122         }
3123
3124         iommu = device_to_iommu(pci_domain_nr(pdev->bus), pdev->bus->number,
3125                                 pdev->devfn);
3126         if (!iommu)
3127                 return -ENODEV;
3128
3129         /* check if this iommu agaw is sufficient for max mapped address */
3130         addr_width = agaw_to_width(iommu->agaw);
3131         end = DOMAIN_MAX_ADDR(addr_width);
3132         end = end & VTD_PAGE_MASK;
3133         if (end < dmar_domain->max_addr) {
3134                 printk(KERN_ERR "%s: iommu agaw (%d) is not "
3135                        "sufficient for the mapped address (%llx)\n",
3136                        __func__, iommu->agaw, dmar_domain->max_addr);
3137                 return -EFAULT;
3138         }
3139
3140         ret = domain_context_mapping(dmar_domain, pdev);
3141         if (ret)
3142                 return ret;
3143
3144         ret = vm_domain_add_dev_info(dmar_domain, pdev);
3145         return ret;
3146 }
3147
3148 static void intel_iommu_detach_device(struct iommu_domain *domain,
3149                                       struct device *dev)
3150 {
3151         struct dmar_domain *dmar_domain = domain->priv;
3152         struct pci_dev *pdev = to_pci_dev(dev);
3153
3154         vm_domain_remove_one_dev_info(dmar_domain, pdev);
3155 }
3156
3157 static int intel_iommu_map_range(struct iommu_domain *domain,
3158                                  unsigned long iova, phys_addr_t hpa,
3159                                  size_t size, int iommu_prot)
3160 {
3161         struct dmar_domain *dmar_domain = domain->priv;
3162         u64 max_addr;
3163         int addr_width;
3164         int prot = 0;
3165         int ret;
3166
3167         if (iommu_prot & IOMMU_READ)
3168                 prot |= DMA_PTE_READ;
3169         if (iommu_prot & IOMMU_WRITE)
3170                 prot |= DMA_PTE_WRITE;
3171         if ((iommu_prot & IOMMU_CACHE) && dmar_domain->iommu_snooping)
3172                 prot |= DMA_PTE_SNP;
3173
3174         max_addr = (iova & VTD_PAGE_MASK) + VTD_PAGE_ALIGN(size);
3175         if (dmar_domain->max_addr < max_addr) {
3176                 int min_agaw;
3177                 u64 end;
3178
3179                 /* check if minimum agaw is sufficient for mapped address */
3180                 min_agaw = vm_domain_min_agaw(dmar_domain);
3181                 addr_width = agaw_to_width(min_agaw);
3182                 end = DOMAIN_MAX_ADDR(addr_width);
3183                 end = end & VTD_PAGE_MASK;
3184                 if (end < max_addr) {
3185                         printk(KERN_ERR "%s: iommu agaw (%d) is not "
3186                                "sufficient for the mapped address (%llx)\n",
3187                                __func__, min_agaw, max_addr);
3188                         return -EFAULT;
3189                 }
3190                 dmar_domain->max_addr = max_addr;
3191         }
3192
3193         ret = domain_page_mapping(dmar_domain, iova, hpa, size, prot);
3194         return ret;
3195 }
3196
3197 static void intel_iommu_unmap_range(struct iommu_domain *domain,
3198                                     unsigned long iova, size_t size)
3199 {
3200         struct dmar_domain *dmar_domain = domain->priv;
3201         dma_addr_t base;
3202
3203         /* The address might not be aligned */
3204         base = iova & VTD_PAGE_MASK;
3205         size = VTD_PAGE_ALIGN(size);
3206         dma_pte_clear_range(dmar_domain, base, base + size);
3207
3208         if (dmar_domain->max_addr == base + size)
3209                 dmar_domain->max_addr = base;
3210 }
3211
3212 static phys_addr_t intel_iommu_iova_to_phys(struct iommu_domain *domain,
3213                                             unsigned long iova)
3214 {
3215         struct dmar_domain *dmar_domain = domain->priv;
3216         struct dma_pte *pte;
3217         u64 phys = 0;
3218
3219         pte = addr_to_dma_pte(dmar_domain, iova);
3220         if (pte)
3221                 phys = dma_pte_addr(pte);
3222
3223         return phys;
3224 }
3225
3226 static int intel_iommu_domain_has_cap(struct iommu_domain *domain,
3227                                       unsigned long cap)
3228 {
3229         struct dmar_domain *dmar_domain = domain->priv;
3230
3231         if (cap == IOMMU_CAP_CACHE_COHERENCY)
3232                 return dmar_domain->iommu_snooping;
3233
3234         return 0;
3235 }
3236
3237 static struct iommu_ops intel_iommu_ops = {
3238         .domain_init    = intel_iommu_domain_init,
3239         .domain_destroy = intel_iommu_domain_destroy,
3240         .attach_dev     = intel_iommu_attach_device,
3241         .detach_dev     = intel_iommu_detach_device,
3242         .map            = intel_iommu_map_range,
3243         .unmap          = intel_iommu_unmap_range,
3244         .iova_to_phys   = intel_iommu_iova_to_phys,
3245         .domain_has_cap = intel_iommu_domain_has_cap,
3246 };
3247
3248 static void __devinit quirk_iommu_rwbf(struct pci_dev *dev)
3249 {
3250         /*
3251          * Mobile 4 Series Chipset neglects to set RWBF capability,
3252          * but needs it:
3253          */
3254         printk(KERN_INFO "DMAR: Forcing write-buffer flush capability\n");
3255         rwbf_quirk = 1;
3256 }
3257
3258 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_rwbf);