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