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