Merge branch 'linus' into irq/numa
[linux-3.10.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         /*
1976          * For each rmrr
1977          *   for each dev attached to rmrr
1978          *   do
1979          *     locate drhd for dev, alloc domain for dev
1980          *     allocate free domain
1981          *     allocate page table entries for rmrr
1982          *     if context not allocated for bus
1983          *           allocate and init context
1984          *           set present in root table for this bus
1985          *     init context with domain, translation etc
1986          *    endfor
1987          * endfor
1988          */
1989         for_each_rmrr_units(rmrr) {
1990                 for (i = 0; i < rmrr->devices_cnt; i++) {
1991                         pdev = rmrr->devices[i];
1992                         /* some BIOS lists non-exist devices in DMAR table */
1993                         if (!pdev)
1994                                 continue;
1995                         ret = iommu_prepare_rmrr_dev(rmrr, pdev);
1996                         if (ret)
1997                                 printk(KERN_ERR
1998                                  "IOMMU: mapping reserved region failed\n");
1999                 }
2000         }
2001
2002         iommu_prepare_gfx_mapping();
2003
2004         iommu_prepare_isa();
2005
2006         /*
2007          * for each drhd
2008          *   enable fault log
2009          *   global invalidate context cache
2010          *   global invalidate iotlb
2011          *   enable translation
2012          */
2013         for_each_drhd_unit(drhd) {
2014                 if (drhd->ignored)
2015                         continue;
2016                 iommu = drhd->iommu;
2017
2018                 iommu_flush_write_buffer(iommu);
2019
2020                 ret = dmar_set_interrupt(iommu);
2021                 if (ret)
2022                         goto error;
2023
2024                 iommu_set_root_entry(iommu);
2025
2026                 iommu->flush.flush_context(iommu, 0, 0, 0, DMA_CCMD_GLOBAL_INVL,
2027                                            0);
2028                 iommu->flush.flush_iotlb(iommu, 0, 0, 0, DMA_TLB_GLOBAL_FLUSH,
2029                                          0);
2030                 iommu_disable_protect_mem_regions(iommu);
2031
2032                 ret = iommu_enable_translation(iommu);
2033                 if (ret)
2034                         goto error;
2035         }
2036
2037         return 0;
2038 error:
2039         for_each_drhd_unit(drhd) {
2040                 if (drhd->ignored)
2041                         continue;
2042                 iommu = drhd->iommu;
2043                 free_iommu(iommu);
2044         }
2045         kfree(g_iommus);
2046         return ret;
2047 }
2048
2049 static inline u64 aligned_size(u64 host_addr, size_t size)
2050 {
2051         u64 addr;
2052         addr = (host_addr & (~PAGE_MASK)) + size;
2053         return PAGE_ALIGN(addr);
2054 }
2055
2056 struct iova *
2057 iommu_alloc_iova(struct dmar_domain *domain, size_t size, u64 end)
2058 {
2059         struct iova *piova;
2060
2061         /* Make sure it's in range */
2062         end = min_t(u64, DOMAIN_MAX_ADDR(domain->gaw), end);
2063         if (!size || (IOVA_START_ADDR + size > end))
2064                 return NULL;
2065
2066         piova = alloc_iova(&domain->iovad,
2067                         size >> PAGE_SHIFT, IOVA_PFN(end), 1);
2068         return piova;
2069 }
2070
2071 static struct iova *
2072 __intel_alloc_iova(struct device *dev, struct dmar_domain *domain,
2073                    size_t size, u64 dma_mask)
2074 {
2075         struct pci_dev *pdev = to_pci_dev(dev);
2076         struct iova *iova = NULL;
2077
2078         if (dma_mask <= DMA_BIT_MASK(32) || dmar_forcedac)
2079                 iova = iommu_alloc_iova(domain, size, dma_mask);
2080         else {
2081                 /*
2082                  * First try to allocate an io virtual address in
2083                  * DMA_BIT_MASK(32) and if that fails then try allocating
2084                  * from higher range
2085                  */
2086                 iova = iommu_alloc_iova(domain, size, DMA_BIT_MASK(32));
2087                 if (!iova)
2088                         iova = iommu_alloc_iova(domain, size, dma_mask);
2089         }
2090
2091         if (!iova) {
2092                 printk(KERN_ERR"Allocating iova for %s failed", pci_name(pdev));
2093                 return NULL;
2094         }
2095
2096         return iova;
2097 }
2098
2099 static struct dmar_domain *
2100 get_valid_domain_for_dev(struct pci_dev *pdev)
2101 {
2102         struct dmar_domain *domain;
2103         int ret;
2104
2105         domain = get_domain_for_dev(pdev,
2106                         DEFAULT_DOMAIN_ADDRESS_WIDTH);
2107         if (!domain) {
2108                 printk(KERN_ERR
2109                         "Allocating domain for %s failed", pci_name(pdev));
2110                 return NULL;
2111         }
2112
2113         /* make sure context mapping is ok */
2114         if (unlikely(!domain_context_mapped(pdev))) {
2115                 ret = domain_context_mapping(domain, pdev);
2116                 if (ret) {
2117                         printk(KERN_ERR
2118                                 "Domain context map for %s failed",
2119                                 pci_name(pdev));
2120                         return NULL;
2121                 }
2122         }
2123
2124         return domain;
2125 }
2126
2127 static dma_addr_t __intel_map_single(struct device *hwdev, phys_addr_t paddr,
2128                                      size_t size, int dir, u64 dma_mask)
2129 {
2130         struct pci_dev *pdev = to_pci_dev(hwdev);
2131         struct dmar_domain *domain;
2132         phys_addr_t start_paddr;
2133         struct iova *iova;
2134         int prot = 0;
2135         int ret;
2136         struct intel_iommu *iommu;
2137
2138         BUG_ON(dir == DMA_NONE);
2139         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2140                 return paddr;
2141
2142         domain = get_valid_domain_for_dev(pdev);
2143         if (!domain)
2144                 return 0;
2145
2146         iommu = domain_get_iommu(domain);
2147         size = aligned_size((u64)paddr, size);
2148
2149         iova = __intel_alloc_iova(hwdev, domain, size, pdev->dma_mask);
2150         if (!iova)
2151                 goto error;
2152
2153         start_paddr = (phys_addr_t)iova->pfn_lo << PAGE_SHIFT;
2154
2155         /*
2156          * Check if DMAR supports zero-length reads on write only
2157          * mappings..
2158          */
2159         if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
2160                         !cap_zlr(iommu->cap))
2161                 prot |= DMA_PTE_READ;
2162         if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
2163                 prot |= DMA_PTE_WRITE;
2164         /*
2165          * paddr - (paddr + size) might be partial page, we should map the whole
2166          * page.  Note: if two part of one page are separately mapped, we
2167          * might have two guest_addr mapping to the same host paddr, but this
2168          * is not a big problem
2169          */
2170         ret = domain_page_mapping(domain, start_paddr,
2171                                   ((u64)paddr) & PHYSICAL_PAGE_MASK,
2172                                   size, prot);
2173         if (ret)
2174                 goto error;
2175
2176         /* it's a non-present to present mapping */
2177         ret = iommu_flush_iotlb_psi(iommu, domain->id,
2178                         start_paddr, size >> VTD_PAGE_SHIFT, 1);
2179         if (ret)
2180                 iommu_flush_write_buffer(iommu);
2181
2182         return start_paddr + ((u64)paddr & (~PAGE_MASK));
2183
2184 error:
2185         if (iova)
2186                 __free_iova(&domain->iovad, iova);
2187         printk(KERN_ERR"Device %s request: %zx@%llx dir %d --- failed\n",
2188                 pci_name(pdev), size, (unsigned long long)paddr, dir);
2189         return 0;
2190 }
2191
2192 static dma_addr_t intel_map_page(struct device *dev, struct page *page,
2193                                  unsigned long offset, size_t size,
2194                                  enum dma_data_direction dir,
2195                                  struct dma_attrs *attrs)
2196 {
2197         return __intel_map_single(dev, page_to_phys(page) + offset, size,
2198                                   dir, to_pci_dev(dev)->dma_mask);
2199 }
2200
2201 static void flush_unmaps(void)
2202 {
2203         int i, j;
2204
2205         timer_on = 0;
2206
2207         /* just flush them all */
2208         for (i = 0; i < g_num_of_iommus; i++) {
2209                 struct intel_iommu *iommu = g_iommus[i];
2210                 if (!iommu)
2211                         continue;
2212
2213                 if (deferred_flush[i].next) {
2214                         iommu->flush.flush_iotlb(iommu, 0, 0, 0,
2215                                                  DMA_TLB_GLOBAL_FLUSH, 0);
2216                         for (j = 0; j < deferred_flush[i].next; j++) {
2217                                 __free_iova(&deferred_flush[i].domain[j]->iovad,
2218                                                 deferred_flush[i].iova[j]);
2219                         }
2220                         deferred_flush[i].next = 0;
2221                 }
2222         }
2223
2224         list_size = 0;
2225 }
2226
2227 static void flush_unmaps_timeout(unsigned long data)
2228 {
2229         unsigned long flags;
2230
2231         spin_lock_irqsave(&async_umap_flush_lock, flags);
2232         flush_unmaps();
2233         spin_unlock_irqrestore(&async_umap_flush_lock, flags);
2234 }
2235
2236 static void add_unmap(struct dmar_domain *dom, struct iova *iova)
2237 {
2238         unsigned long flags;
2239         int next, iommu_id;
2240         struct intel_iommu *iommu;
2241
2242         spin_lock_irqsave(&async_umap_flush_lock, flags);
2243         if (list_size == HIGH_WATER_MARK)
2244                 flush_unmaps();
2245
2246         iommu = domain_get_iommu(dom);
2247         iommu_id = iommu->seq_id;
2248
2249         next = deferred_flush[iommu_id].next;
2250         deferred_flush[iommu_id].domain[next] = dom;
2251         deferred_flush[iommu_id].iova[next] = iova;
2252         deferred_flush[iommu_id].next++;
2253
2254         if (!timer_on) {
2255                 mod_timer(&unmap_timer, jiffies + msecs_to_jiffies(10));
2256                 timer_on = 1;
2257         }
2258         list_size++;
2259         spin_unlock_irqrestore(&async_umap_flush_lock, flags);
2260 }
2261
2262 static void intel_unmap_page(struct device *dev, dma_addr_t dev_addr,
2263                              size_t size, enum dma_data_direction dir,
2264                              struct dma_attrs *attrs)
2265 {
2266         struct pci_dev *pdev = to_pci_dev(dev);
2267         struct dmar_domain *domain;
2268         unsigned long start_addr;
2269         struct iova *iova;
2270         struct intel_iommu *iommu;
2271
2272         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2273                 return;
2274         domain = find_domain(pdev);
2275         BUG_ON(!domain);
2276
2277         iommu = domain_get_iommu(domain);
2278
2279         iova = find_iova(&domain->iovad, IOVA_PFN(dev_addr));
2280         if (!iova)
2281                 return;
2282
2283         start_addr = iova->pfn_lo << PAGE_SHIFT;
2284         size = aligned_size((u64)dev_addr, size);
2285
2286         pr_debug("Device %s unmapping: %zx@%llx\n",
2287                 pci_name(pdev), size, (unsigned long long)start_addr);
2288
2289         /*  clear the whole page */
2290         dma_pte_clear_range(domain, start_addr, start_addr + size);
2291         /* free page tables */
2292         dma_pte_free_pagetable(domain, start_addr, start_addr + size);
2293         if (intel_iommu_strict) {
2294                 if (iommu_flush_iotlb_psi(iommu,
2295                         domain->id, start_addr, size >> VTD_PAGE_SHIFT, 0))
2296                         iommu_flush_write_buffer(iommu);
2297                 /* free iova */
2298                 __free_iova(&domain->iovad, iova);
2299         } else {
2300                 add_unmap(domain, iova);
2301                 /*
2302                  * queue up the release of the unmap to save the 1/6th of the
2303                  * cpu used up by the iotlb flush operation...
2304                  */
2305         }
2306 }
2307
2308 static void intel_unmap_single(struct device *dev, dma_addr_t dev_addr, size_t size,
2309                                int dir)
2310 {
2311         intel_unmap_page(dev, dev_addr, size, dir, NULL);
2312 }
2313
2314 static void *intel_alloc_coherent(struct device *hwdev, size_t size,
2315                                   dma_addr_t *dma_handle, gfp_t flags)
2316 {
2317         void *vaddr;
2318         int order;
2319
2320         size = PAGE_ALIGN(size);
2321         order = get_order(size);
2322         flags &= ~(GFP_DMA | GFP_DMA32);
2323
2324         vaddr = (void *)__get_free_pages(flags, order);
2325         if (!vaddr)
2326                 return NULL;
2327         memset(vaddr, 0, size);
2328
2329         *dma_handle = __intel_map_single(hwdev, virt_to_bus(vaddr), size,
2330                                          DMA_BIDIRECTIONAL,
2331                                          hwdev->coherent_dma_mask);
2332         if (*dma_handle)
2333                 return vaddr;
2334         free_pages((unsigned long)vaddr, order);
2335         return NULL;
2336 }
2337
2338 static void intel_free_coherent(struct device *hwdev, size_t size, void *vaddr,
2339                                 dma_addr_t dma_handle)
2340 {
2341         int order;
2342
2343         size = PAGE_ALIGN(size);
2344         order = get_order(size);
2345
2346         intel_unmap_single(hwdev, dma_handle, size, DMA_BIDIRECTIONAL);
2347         free_pages((unsigned long)vaddr, order);
2348 }
2349
2350 static void intel_unmap_sg(struct device *hwdev, struct scatterlist *sglist,
2351                            int nelems, enum dma_data_direction dir,
2352                            struct dma_attrs *attrs)
2353 {
2354         int i;
2355         struct pci_dev *pdev = to_pci_dev(hwdev);
2356         struct dmar_domain *domain;
2357         unsigned long start_addr;
2358         struct iova *iova;
2359         size_t size = 0;
2360         phys_addr_t addr;
2361         struct scatterlist *sg;
2362         struct intel_iommu *iommu;
2363
2364         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2365                 return;
2366
2367         domain = find_domain(pdev);
2368         BUG_ON(!domain);
2369
2370         iommu = domain_get_iommu(domain);
2371
2372         iova = find_iova(&domain->iovad, IOVA_PFN(sglist[0].dma_address));
2373         if (!iova)
2374                 return;
2375         for_each_sg(sglist, sg, nelems, i) {
2376                 addr = page_to_phys(sg_page(sg)) + sg->offset;
2377                 size += aligned_size((u64)addr, sg->length);
2378         }
2379
2380         start_addr = iova->pfn_lo << PAGE_SHIFT;
2381
2382         /*  clear the whole page */
2383         dma_pte_clear_range(domain, start_addr, start_addr + size);
2384         /* free page tables */
2385         dma_pte_free_pagetable(domain, start_addr, start_addr + size);
2386
2387         if (iommu_flush_iotlb_psi(iommu, domain->id, start_addr,
2388                         size >> VTD_PAGE_SHIFT, 0))
2389                 iommu_flush_write_buffer(iommu);
2390
2391         /* free iova */
2392         __free_iova(&domain->iovad, iova);
2393 }
2394
2395 static int intel_nontranslate_map_sg(struct device *hddev,
2396         struct scatterlist *sglist, int nelems, int dir)
2397 {
2398         int i;
2399         struct scatterlist *sg;
2400
2401         for_each_sg(sglist, sg, nelems, i) {
2402                 BUG_ON(!sg_page(sg));
2403                 sg->dma_address = page_to_phys(sg_page(sg)) + sg->offset;
2404                 sg->dma_length = sg->length;
2405         }
2406         return nelems;
2407 }
2408
2409 static int intel_map_sg(struct device *hwdev, struct scatterlist *sglist, int nelems,
2410                         enum dma_data_direction dir, struct dma_attrs *attrs)
2411 {
2412         phys_addr_t addr;
2413         int i;
2414         struct pci_dev *pdev = to_pci_dev(hwdev);
2415         struct dmar_domain *domain;
2416         size_t size = 0;
2417         int prot = 0;
2418         size_t offset = 0;
2419         struct iova *iova = NULL;
2420         int ret;
2421         struct scatterlist *sg;
2422         unsigned long start_addr;
2423         struct intel_iommu *iommu;
2424
2425         BUG_ON(dir == DMA_NONE);
2426         if (pdev->dev.archdata.iommu == DUMMY_DEVICE_DOMAIN_INFO)
2427                 return intel_nontranslate_map_sg(hwdev, sglist, nelems, dir);
2428
2429         domain = get_valid_domain_for_dev(pdev);
2430         if (!domain)
2431                 return 0;
2432
2433         iommu = domain_get_iommu(domain);
2434
2435         for_each_sg(sglist, sg, nelems, i) {
2436                 addr = page_to_phys(sg_page(sg)) + sg->offset;
2437                 size += aligned_size((u64)addr, sg->length);
2438         }
2439
2440         iova = __intel_alloc_iova(hwdev, domain, size, pdev->dma_mask);
2441         if (!iova) {
2442                 sglist->dma_length = 0;
2443                 return 0;
2444         }
2445
2446         /*
2447          * Check if DMAR supports zero-length reads on write only
2448          * mappings..
2449          */
2450         if (dir == DMA_TO_DEVICE || dir == DMA_BIDIRECTIONAL || \
2451                         !cap_zlr(iommu->cap))
2452                 prot |= DMA_PTE_READ;
2453         if (dir == DMA_FROM_DEVICE || dir == DMA_BIDIRECTIONAL)
2454                 prot |= DMA_PTE_WRITE;
2455
2456         start_addr = iova->pfn_lo << PAGE_SHIFT;
2457         offset = 0;
2458         for_each_sg(sglist, sg, nelems, i) {
2459                 addr = page_to_phys(sg_page(sg)) + sg->offset;
2460                 size = aligned_size((u64)addr, sg->length);
2461                 ret = domain_page_mapping(domain, start_addr + offset,
2462                                           ((u64)addr) & PHYSICAL_PAGE_MASK,
2463                                           size, prot);
2464                 if (ret) {
2465                         /*  clear the page */
2466                         dma_pte_clear_range(domain, start_addr,
2467                                   start_addr + offset);
2468                         /* free page tables */
2469                         dma_pte_free_pagetable(domain, start_addr,
2470                                   start_addr + offset);
2471                         /* free iova */
2472                         __free_iova(&domain->iovad, iova);
2473                         return 0;
2474                 }
2475                 sg->dma_address = start_addr + offset +
2476                                 ((u64)addr & (~PAGE_MASK));
2477                 sg->dma_length = sg->length;
2478                 offset += size;
2479         }
2480
2481         /* it's a non-present to present mapping */
2482         if (iommu_flush_iotlb_psi(iommu, domain->id,
2483                         start_addr, offset >> VTD_PAGE_SHIFT, 1))
2484                 iommu_flush_write_buffer(iommu);
2485         return nelems;
2486 }
2487
2488 static int intel_mapping_error(struct device *dev, dma_addr_t dma_addr)
2489 {
2490         return !dma_addr;
2491 }
2492
2493 struct dma_map_ops intel_dma_ops = {
2494         .alloc_coherent = intel_alloc_coherent,
2495         .free_coherent = intel_free_coherent,
2496         .map_sg = intel_map_sg,
2497         .unmap_sg = intel_unmap_sg,
2498         .map_page = intel_map_page,
2499         .unmap_page = intel_unmap_page,
2500         .mapping_error = intel_mapping_error,
2501 };
2502
2503 static inline int iommu_domain_cache_init(void)
2504 {
2505         int ret = 0;
2506
2507         iommu_domain_cache = kmem_cache_create("iommu_domain",
2508                                          sizeof(struct dmar_domain),
2509                                          0,
2510                                          SLAB_HWCACHE_ALIGN,
2511
2512                                          NULL);
2513         if (!iommu_domain_cache) {
2514                 printk(KERN_ERR "Couldn't create iommu_domain cache\n");
2515                 ret = -ENOMEM;
2516         }
2517
2518         return ret;
2519 }
2520
2521 static inline int iommu_devinfo_cache_init(void)
2522 {
2523         int ret = 0;
2524
2525         iommu_devinfo_cache = kmem_cache_create("iommu_devinfo",
2526                                          sizeof(struct device_domain_info),
2527                                          0,
2528                                          SLAB_HWCACHE_ALIGN,
2529                                          NULL);
2530         if (!iommu_devinfo_cache) {
2531                 printk(KERN_ERR "Couldn't create devinfo cache\n");
2532                 ret = -ENOMEM;
2533         }
2534
2535         return ret;
2536 }
2537
2538 static inline int iommu_iova_cache_init(void)
2539 {
2540         int ret = 0;
2541
2542         iommu_iova_cache = kmem_cache_create("iommu_iova",
2543                                          sizeof(struct iova),
2544                                          0,
2545                                          SLAB_HWCACHE_ALIGN,
2546                                          NULL);
2547         if (!iommu_iova_cache) {
2548                 printk(KERN_ERR "Couldn't create iova cache\n");
2549                 ret = -ENOMEM;
2550         }
2551
2552         return ret;
2553 }
2554
2555 static int __init iommu_init_mempool(void)
2556 {
2557         int ret;
2558         ret = iommu_iova_cache_init();
2559         if (ret)
2560                 return ret;
2561
2562         ret = iommu_domain_cache_init();
2563         if (ret)
2564                 goto domain_error;
2565
2566         ret = iommu_devinfo_cache_init();
2567         if (!ret)
2568                 return ret;
2569
2570         kmem_cache_destroy(iommu_domain_cache);
2571 domain_error:
2572         kmem_cache_destroy(iommu_iova_cache);
2573
2574         return -ENOMEM;
2575 }
2576
2577 static void __init iommu_exit_mempool(void)
2578 {
2579         kmem_cache_destroy(iommu_devinfo_cache);
2580         kmem_cache_destroy(iommu_domain_cache);
2581         kmem_cache_destroy(iommu_iova_cache);
2582
2583 }
2584
2585 static void __init init_no_remapping_devices(void)
2586 {
2587         struct dmar_drhd_unit *drhd;
2588
2589         for_each_drhd_unit(drhd) {
2590                 if (!drhd->include_all) {
2591                         int i;
2592                         for (i = 0; i < drhd->devices_cnt; i++)
2593                                 if (drhd->devices[i] != NULL)
2594                                         break;
2595                         /* ignore DMAR unit if no pci devices exist */
2596                         if (i == drhd->devices_cnt)
2597                                 drhd->ignored = 1;
2598                 }
2599         }
2600
2601         if (dmar_map_gfx)
2602                 return;
2603
2604         for_each_drhd_unit(drhd) {
2605                 int i;
2606                 if (drhd->ignored || drhd->include_all)
2607                         continue;
2608
2609                 for (i = 0; i < drhd->devices_cnt; i++)
2610                         if (drhd->devices[i] &&
2611                                 !IS_GFX_DEVICE(drhd->devices[i]))
2612                                 break;
2613
2614                 if (i < drhd->devices_cnt)
2615                         continue;
2616
2617                 /* bypass IOMMU if it is just for gfx devices */
2618                 drhd->ignored = 1;
2619                 for (i = 0; i < drhd->devices_cnt; i++) {
2620                         if (!drhd->devices[i])
2621                                 continue;
2622                         drhd->devices[i]->dev.archdata.iommu = DUMMY_DEVICE_DOMAIN_INFO;
2623                 }
2624         }
2625 }
2626
2627 #ifdef CONFIG_SUSPEND
2628 static int init_iommu_hw(void)
2629 {
2630         struct dmar_drhd_unit *drhd;
2631         struct intel_iommu *iommu = NULL;
2632
2633         for_each_active_iommu(iommu, drhd)
2634                 if (iommu->qi)
2635                         dmar_reenable_qi(iommu);
2636
2637         for_each_active_iommu(iommu, drhd) {
2638                 iommu_flush_write_buffer(iommu);
2639
2640                 iommu_set_root_entry(iommu);
2641
2642                 iommu->flush.flush_context(iommu, 0, 0, 0,
2643                                                 DMA_CCMD_GLOBAL_INVL, 0);
2644                 iommu->flush.flush_iotlb(iommu, 0, 0, 0,
2645                                                 DMA_TLB_GLOBAL_FLUSH, 0);
2646                 iommu_disable_protect_mem_regions(iommu);
2647                 iommu_enable_translation(iommu);
2648         }
2649
2650         return 0;
2651 }
2652
2653 static void iommu_flush_all(void)
2654 {
2655         struct dmar_drhd_unit *drhd;
2656         struct intel_iommu *iommu;
2657
2658         for_each_active_iommu(iommu, drhd) {
2659                 iommu->flush.flush_context(iommu, 0, 0, 0,
2660                                                 DMA_CCMD_GLOBAL_INVL, 0);
2661                 iommu->flush.flush_iotlb(iommu, 0, 0, 0,
2662                                                 DMA_TLB_GLOBAL_FLUSH, 0);
2663         }
2664 }
2665
2666 static int iommu_suspend(struct sys_device *dev, pm_message_t state)
2667 {
2668         struct dmar_drhd_unit *drhd;
2669         struct intel_iommu *iommu = NULL;
2670         unsigned long flag;
2671
2672         for_each_active_iommu(iommu, drhd) {
2673                 iommu->iommu_state = kzalloc(sizeof(u32) * MAX_SR_DMAR_REGS,
2674                                                  GFP_ATOMIC);
2675                 if (!iommu->iommu_state)
2676                         goto nomem;
2677         }
2678
2679         iommu_flush_all();
2680
2681         for_each_active_iommu(iommu, drhd) {
2682                 iommu_disable_translation(iommu);
2683
2684                 spin_lock_irqsave(&iommu->register_lock, flag);
2685
2686                 iommu->iommu_state[SR_DMAR_FECTL_REG] =
2687                         readl(iommu->reg + DMAR_FECTL_REG);
2688                 iommu->iommu_state[SR_DMAR_FEDATA_REG] =
2689                         readl(iommu->reg + DMAR_FEDATA_REG);
2690                 iommu->iommu_state[SR_DMAR_FEADDR_REG] =
2691                         readl(iommu->reg + DMAR_FEADDR_REG);
2692                 iommu->iommu_state[SR_DMAR_FEUADDR_REG] =
2693                         readl(iommu->reg + DMAR_FEUADDR_REG);
2694
2695                 spin_unlock_irqrestore(&iommu->register_lock, flag);
2696         }
2697         return 0;
2698
2699 nomem:
2700         for_each_active_iommu(iommu, drhd)
2701                 kfree(iommu->iommu_state);
2702
2703         return -ENOMEM;
2704 }
2705
2706 static int iommu_resume(struct sys_device *dev)
2707 {
2708         struct dmar_drhd_unit *drhd;
2709         struct intel_iommu *iommu = NULL;
2710         unsigned long flag;
2711
2712         if (init_iommu_hw()) {
2713                 WARN(1, "IOMMU setup failed, DMAR can not resume!\n");
2714                 return -EIO;
2715         }
2716
2717         for_each_active_iommu(iommu, drhd) {
2718
2719                 spin_lock_irqsave(&iommu->register_lock, flag);
2720
2721                 writel(iommu->iommu_state[SR_DMAR_FECTL_REG],
2722                         iommu->reg + DMAR_FECTL_REG);
2723                 writel(iommu->iommu_state[SR_DMAR_FEDATA_REG],
2724                         iommu->reg + DMAR_FEDATA_REG);
2725                 writel(iommu->iommu_state[SR_DMAR_FEADDR_REG],
2726                         iommu->reg + DMAR_FEADDR_REG);
2727                 writel(iommu->iommu_state[SR_DMAR_FEUADDR_REG],
2728                         iommu->reg + DMAR_FEUADDR_REG);
2729
2730                 spin_unlock_irqrestore(&iommu->register_lock, flag);
2731         }
2732
2733         for_each_active_iommu(iommu, drhd)
2734                 kfree(iommu->iommu_state);
2735
2736         return 0;
2737 }
2738
2739 static struct sysdev_class iommu_sysclass = {
2740         .name           = "iommu",
2741         .resume         = iommu_resume,
2742         .suspend        = iommu_suspend,
2743 };
2744
2745 static struct sys_device device_iommu = {
2746         .cls    = &iommu_sysclass,
2747 };
2748
2749 static int __init init_iommu_sysfs(void)
2750 {
2751         int error;
2752
2753         error = sysdev_class_register(&iommu_sysclass);
2754         if (error)
2755                 return error;
2756
2757         error = sysdev_register(&device_iommu);
2758         if (error)
2759                 sysdev_class_unregister(&iommu_sysclass);
2760
2761         return error;
2762 }
2763
2764 #else
2765 static int __init init_iommu_sysfs(void)
2766 {
2767         return 0;
2768 }
2769 #endif  /* CONFIG_PM */
2770
2771 int __init intel_iommu_init(void)
2772 {
2773         int ret = 0;
2774
2775         if (dmar_table_init())
2776                 return  -ENODEV;
2777
2778         if (dmar_dev_scope_init())
2779                 return  -ENODEV;
2780
2781         /*
2782          * Check the need for DMA-remapping initialization now.
2783          * Above initialization will also be used by Interrupt-remapping.
2784          */
2785         if (no_iommu || swiotlb || dmar_disabled)
2786                 return -ENODEV;
2787
2788         iommu_init_mempool();
2789         dmar_init_reserved_ranges();
2790
2791         init_no_remapping_devices();
2792
2793         ret = init_dmars();
2794         if (ret) {
2795                 printk(KERN_ERR "IOMMU: dmar init failed\n");
2796                 put_iova_domain(&reserved_iova_list);
2797                 iommu_exit_mempool();
2798                 return ret;
2799         }
2800         printk(KERN_INFO
2801         "PCI-DMA: Intel(R) Virtualization Technology for Directed I/O\n");
2802
2803         init_timer(&unmap_timer);
2804         force_iommu = 1;
2805         dma_ops = &intel_dma_ops;
2806         init_iommu_sysfs();
2807
2808         register_iommu(&intel_iommu_ops);
2809
2810         return 0;
2811 }
2812
2813 static int vm_domain_add_dev_info(struct dmar_domain *domain,
2814                                   struct pci_dev *pdev)
2815 {
2816         struct device_domain_info *info;
2817         unsigned long flags;
2818
2819         info = alloc_devinfo_mem();
2820         if (!info)
2821                 return -ENOMEM;
2822
2823         info->segment = pci_domain_nr(pdev->bus);
2824         info->bus = pdev->bus->number;
2825         info->devfn = pdev->devfn;
2826         info->dev = pdev;
2827         info->domain = domain;
2828
2829         spin_lock_irqsave(&device_domain_lock, flags);
2830         list_add(&info->link, &domain->devices);
2831         list_add(&info->global, &device_domain_list);
2832         pdev->dev.archdata.iommu = info;
2833         spin_unlock_irqrestore(&device_domain_lock, flags);
2834
2835         return 0;
2836 }
2837
2838 static void iommu_detach_dependent_devices(struct intel_iommu *iommu,
2839                                            struct pci_dev *pdev)
2840 {
2841         struct pci_dev *tmp, *parent;
2842
2843         if (!iommu || !pdev)
2844                 return;
2845
2846         /* dependent device detach */
2847         tmp = pci_find_upstream_pcie_bridge(pdev);
2848         /* Secondary interface's bus number and devfn 0 */
2849         if (tmp) {
2850                 parent = pdev->bus->self;
2851                 while (parent != tmp) {
2852                         iommu_detach_dev(iommu, parent->bus->number,
2853                                          parent->devfn);
2854                         parent = parent->bus->self;
2855                 }
2856                 if (tmp->is_pcie) /* this is a PCIE-to-PCI bridge */
2857                         iommu_detach_dev(iommu,
2858                                 tmp->subordinate->number, 0);
2859                 else /* this is a legacy PCI bridge */
2860                         iommu_detach_dev(iommu, tmp->bus->number,
2861                                          tmp->devfn);
2862         }
2863 }
2864
2865 static void vm_domain_remove_one_dev_info(struct dmar_domain *domain,
2866                                           struct pci_dev *pdev)
2867 {
2868         struct device_domain_info *info;
2869         struct intel_iommu *iommu;
2870         unsigned long flags;
2871         int found = 0;
2872         struct list_head *entry, *tmp;
2873
2874         iommu = device_to_iommu(pci_domain_nr(pdev->bus), pdev->bus->number,
2875                                 pdev->devfn);
2876         if (!iommu)
2877                 return;
2878
2879         spin_lock_irqsave(&device_domain_lock, flags);
2880         list_for_each_safe(entry, tmp, &domain->devices) {
2881                 info = list_entry(entry, struct device_domain_info, link);
2882                 /* No need to compare PCI domain; it has to be the same */
2883                 if (info->bus == pdev->bus->number &&
2884                     info->devfn == pdev->devfn) {
2885                         list_del(&info->link);
2886                         list_del(&info->global);
2887                         if (info->dev)
2888                                 info->dev->dev.archdata.iommu = NULL;
2889                         spin_unlock_irqrestore(&device_domain_lock, flags);
2890
2891                         iommu_detach_dev(iommu, info->bus, info->devfn);
2892                         iommu_detach_dependent_devices(iommu, pdev);
2893                         free_devinfo_mem(info);
2894
2895                         spin_lock_irqsave(&device_domain_lock, flags);
2896
2897                         if (found)
2898                                 break;
2899                         else
2900                                 continue;
2901                 }
2902
2903                 /* if there is no other devices under the same iommu
2904                  * owned by this domain, clear this iommu in iommu_bmp
2905                  * update iommu count and coherency
2906                  */
2907                 if (iommu == device_to_iommu(info->segment, info->bus,
2908                                             info->devfn))
2909                         found = 1;
2910         }
2911
2912         if (found == 0) {
2913                 unsigned long tmp_flags;
2914                 spin_lock_irqsave(&domain->iommu_lock, tmp_flags);
2915                 clear_bit(iommu->seq_id, &domain->iommu_bmp);
2916                 domain->iommu_count--;
2917                 domain_update_iommu_cap(domain);
2918                 spin_unlock_irqrestore(&domain->iommu_lock, tmp_flags);
2919         }
2920
2921         spin_unlock_irqrestore(&device_domain_lock, flags);
2922 }
2923
2924 static void vm_domain_remove_all_dev_info(struct dmar_domain *domain)
2925 {
2926         struct device_domain_info *info;
2927         struct intel_iommu *iommu;
2928         unsigned long flags1, flags2;
2929
2930         spin_lock_irqsave(&device_domain_lock, flags1);
2931         while (!list_empty(&domain->devices)) {
2932                 info = list_entry(domain->devices.next,
2933                         struct device_domain_info, link);
2934                 list_del(&info->link);
2935                 list_del(&info->global);
2936                 if (info->dev)
2937                         info->dev->dev.archdata.iommu = NULL;
2938
2939                 spin_unlock_irqrestore(&device_domain_lock, flags1);
2940
2941                 iommu = device_to_iommu(info->segment, info->bus, info->devfn);
2942                 iommu_detach_dev(iommu, info->bus, info->devfn);
2943                 iommu_detach_dependent_devices(iommu, info->dev);
2944
2945                 /* clear this iommu in iommu_bmp, update iommu count
2946                  * and capabilities
2947                  */
2948                 spin_lock_irqsave(&domain->iommu_lock, flags2);
2949                 if (test_and_clear_bit(iommu->seq_id,
2950                                        &domain->iommu_bmp)) {
2951                         domain->iommu_count--;
2952                         domain_update_iommu_cap(domain);
2953                 }
2954                 spin_unlock_irqrestore(&domain->iommu_lock, flags2);
2955
2956                 free_devinfo_mem(info);
2957                 spin_lock_irqsave(&device_domain_lock, flags1);
2958         }
2959         spin_unlock_irqrestore(&device_domain_lock, flags1);
2960 }
2961
2962 /* domain id for virtual machine, it won't be set in context */
2963 static unsigned long vm_domid;
2964
2965 static int vm_domain_min_agaw(struct dmar_domain *domain)
2966 {
2967         int i;
2968         int min_agaw = domain->agaw;
2969
2970         i = find_first_bit(&domain->iommu_bmp, g_num_of_iommus);
2971         for (; i < g_num_of_iommus; ) {
2972                 if (min_agaw > g_iommus[i]->agaw)
2973                         min_agaw = g_iommus[i]->agaw;
2974
2975                 i = find_next_bit(&domain->iommu_bmp, g_num_of_iommus, i+1);
2976         }
2977
2978         return min_agaw;
2979 }
2980
2981 static struct dmar_domain *iommu_alloc_vm_domain(void)
2982 {
2983         struct dmar_domain *domain;
2984
2985         domain = alloc_domain_mem();
2986         if (!domain)
2987                 return NULL;
2988
2989         domain->id = vm_domid++;
2990         memset(&domain->iommu_bmp, 0, sizeof(unsigned long));
2991         domain->flags = DOMAIN_FLAG_VIRTUAL_MACHINE;
2992
2993         return domain;
2994 }
2995
2996 static int vm_domain_init(struct dmar_domain *domain, int guest_width)
2997 {
2998         int adjust_width;
2999
3000         init_iova_domain(&domain->iovad, DMA_32BIT_PFN);
3001         spin_lock_init(&domain->mapping_lock);
3002         spin_lock_init(&domain->iommu_lock);
3003
3004         domain_reserve_special_ranges(domain);
3005
3006         /* calculate AGAW */
3007         domain->gaw = guest_width;
3008         adjust_width = guestwidth_to_adjustwidth(guest_width);
3009         domain->agaw = width_to_agaw(adjust_width);
3010
3011         INIT_LIST_HEAD(&domain->devices);
3012
3013         domain->iommu_count = 0;
3014         domain->iommu_coherency = 0;
3015         domain->max_addr = 0;
3016
3017         /* always allocate the top pgd */
3018         domain->pgd = (struct dma_pte *)alloc_pgtable_page();
3019         if (!domain->pgd)
3020                 return -ENOMEM;
3021         domain_flush_cache(domain, domain->pgd, PAGE_SIZE);
3022         return 0;
3023 }
3024
3025 static void iommu_free_vm_domain(struct dmar_domain *domain)
3026 {
3027         unsigned long flags;
3028         struct dmar_drhd_unit *drhd;
3029         struct intel_iommu *iommu;
3030         unsigned long i;
3031         unsigned long ndomains;
3032
3033         for_each_drhd_unit(drhd) {
3034                 if (drhd->ignored)
3035                         continue;
3036                 iommu = drhd->iommu;
3037
3038                 ndomains = cap_ndoms(iommu->cap);
3039                 i = find_first_bit(iommu->domain_ids, ndomains);
3040                 for (; i < ndomains; ) {
3041                         if (iommu->domains[i] == domain) {
3042                                 spin_lock_irqsave(&iommu->lock, flags);
3043                                 clear_bit(i, iommu->domain_ids);
3044                                 iommu->domains[i] = NULL;
3045                                 spin_unlock_irqrestore(&iommu->lock, flags);
3046                                 break;
3047                         }
3048                         i = find_next_bit(iommu->domain_ids, ndomains, i+1);
3049                 }
3050         }
3051 }
3052
3053 static void vm_domain_exit(struct dmar_domain *domain)
3054 {
3055         u64 end;
3056
3057         /* Domain 0 is reserved, so dont process it */
3058         if (!domain)
3059                 return;
3060
3061         vm_domain_remove_all_dev_info(domain);
3062         /* destroy iovas */
3063         put_iova_domain(&domain->iovad);
3064         end = DOMAIN_MAX_ADDR(domain->gaw);
3065         end = end & (~VTD_PAGE_MASK);
3066
3067         /* clear ptes */
3068         dma_pte_clear_range(domain, 0, end);
3069
3070         /* free page tables */
3071         dma_pte_free_pagetable(domain, 0, end);
3072
3073         iommu_free_vm_domain(domain);
3074         free_domain_mem(domain);
3075 }
3076
3077 static int intel_iommu_domain_init(struct iommu_domain *domain)
3078 {
3079         struct dmar_domain *dmar_domain;
3080
3081         dmar_domain = iommu_alloc_vm_domain();
3082         if (!dmar_domain) {
3083                 printk(KERN_ERR
3084                         "intel_iommu_domain_init: dmar_domain == NULL\n");
3085                 return -ENOMEM;
3086         }
3087         if (vm_domain_init(dmar_domain, DEFAULT_DOMAIN_ADDRESS_WIDTH)) {
3088                 printk(KERN_ERR
3089                         "intel_iommu_domain_init() failed\n");
3090                 vm_domain_exit(dmar_domain);
3091                 return -ENOMEM;
3092         }
3093         domain->priv = dmar_domain;
3094
3095         return 0;
3096 }
3097
3098 static void intel_iommu_domain_destroy(struct iommu_domain *domain)
3099 {
3100         struct dmar_domain *dmar_domain = domain->priv;
3101
3102         domain->priv = NULL;
3103         vm_domain_exit(dmar_domain);
3104 }
3105
3106 static int intel_iommu_attach_device(struct iommu_domain *domain,
3107                                      struct device *dev)
3108 {
3109         struct dmar_domain *dmar_domain = domain->priv;
3110         struct pci_dev *pdev = to_pci_dev(dev);
3111         struct intel_iommu *iommu;
3112         int addr_width;
3113         u64 end;
3114         int ret;
3115
3116         /* normally pdev is not mapped */
3117         if (unlikely(domain_context_mapped(pdev))) {
3118                 struct dmar_domain *old_domain;
3119
3120                 old_domain = find_domain(pdev);
3121                 if (old_domain) {
3122                         if (dmar_domain->flags & DOMAIN_FLAG_VIRTUAL_MACHINE)
3123                                 vm_domain_remove_one_dev_info(old_domain, pdev);
3124                         else
3125                                 domain_remove_dev_info(old_domain);
3126                 }
3127         }
3128
3129         iommu = device_to_iommu(pci_domain_nr(pdev->bus), pdev->bus->number,
3130                                 pdev->devfn);
3131         if (!iommu)
3132                 return -ENODEV;
3133
3134         /* check if this iommu agaw is sufficient for max mapped address */
3135         addr_width = agaw_to_width(iommu->agaw);
3136         end = DOMAIN_MAX_ADDR(addr_width);
3137         end = end & VTD_PAGE_MASK;
3138         if (end < dmar_domain->max_addr) {
3139                 printk(KERN_ERR "%s: iommu agaw (%d) is not "
3140                        "sufficient for the mapped address (%llx)\n",
3141                        __func__, iommu->agaw, dmar_domain->max_addr);
3142                 return -EFAULT;
3143         }
3144
3145         ret = domain_context_mapping(dmar_domain, pdev);
3146         if (ret)
3147                 return ret;
3148
3149         ret = vm_domain_add_dev_info(dmar_domain, pdev);
3150         return ret;
3151 }
3152
3153 static void intel_iommu_detach_device(struct iommu_domain *domain,
3154                                       struct device *dev)
3155 {
3156         struct dmar_domain *dmar_domain = domain->priv;
3157         struct pci_dev *pdev = to_pci_dev(dev);
3158
3159         vm_domain_remove_one_dev_info(dmar_domain, pdev);
3160 }
3161
3162 static int intel_iommu_map_range(struct iommu_domain *domain,
3163                                  unsigned long iova, phys_addr_t hpa,
3164                                  size_t size, int iommu_prot)
3165 {
3166         struct dmar_domain *dmar_domain = domain->priv;
3167         u64 max_addr;
3168         int addr_width;
3169         int prot = 0;
3170         int ret;
3171
3172         if (iommu_prot & IOMMU_READ)
3173                 prot |= DMA_PTE_READ;
3174         if (iommu_prot & IOMMU_WRITE)
3175                 prot |= DMA_PTE_WRITE;
3176         if ((iommu_prot & IOMMU_CACHE) && dmar_domain->iommu_snooping)
3177                 prot |= DMA_PTE_SNP;
3178
3179         max_addr = (iova & VTD_PAGE_MASK) + VTD_PAGE_ALIGN(size);
3180         if (dmar_domain->max_addr < max_addr) {
3181                 int min_agaw;
3182                 u64 end;
3183
3184                 /* check if minimum agaw is sufficient for mapped address */
3185                 min_agaw = vm_domain_min_agaw(dmar_domain);
3186                 addr_width = agaw_to_width(min_agaw);
3187                 end = DOMAIN_MAX_ADDR(addr_width);
3188                 end = end & VTD_PAGE_MASK;
3189                 if (end < max_addr) {
3190                         printk(KERN_ERR "%s: iommu agaw (%d) is not "
3191                                "sufficient for the mapped address (%llx)\n",
3192                                __func__, min_agaw, max_addr);
3193                         return -EFAULT;
3194                 }
3195                 dmar_domain->max_addr = max_addr;
3196         }
3197
3198         ret = domain_page_mapping(dmar_domain, iova, hpa, size, prot);
3199         return ret;
3200 }
3201
3202 static void intel_iommu_unmap_range(struct iommu_domain *domain,
3203                                     unsigned long iova, size_t size)
3204 {
3205         struct dmar_domain *dmar_domain = domain->priv;
3206         dma_addr_t base;
3207
3208         /* The address might not be aligned */
3209         base = iova & VTD_PAGE_MASK;
3210         size = VTD_PAGE_ALIGN(size);
3211         dma_pte_clear_range(dmar_domain, base, base + size);
3212
3213         if (dmar_domain->max_addr == base + size)
3214                 dmar_domain->max_addr = base;
3215 }
3216
3217 static phys_addr_t intel_iommu_iova_to_phys(struct iommu_domain *domain,
3218                                             unsigned long iova)
3219 {
3220         struct dmar_domain *dmar_domain = domain->priv;
3221         struct dma_pte *pte;
3222         u64 phys = 0;
3223
3224         pte = addr_to_dma_pte(dmar_domain, iova);
3225         if (pte)
3226                 phys = dma_pte_addr(pte);
3227
3228         return phys;
3229 }
3230
3231 static int intel_iommu_domain_has_cap(struct iommu_domain *domain,
3232                                       unsigned long cap)
3233 {
3234         struct dmar_domain *dmar_domain = domain->priv;
3235
3236         if (cap == IOMMU_CAP_CACHE_COHERENCY)
3237                 return dmar_domain->iommu_snooping;
3238
3239         return 0;
3240 }
3241
3242 static struct iommu_ops intel_iommu_ops = {
3243         .domain_init    = intel_iommu_domain_init,
3244         .domain_destroy = intel_iommu_domain_destroy,
3245         .attach_dev     = intel_iommu_attach_device,
3246         .detach_dev     = intel_iommu_detach_device,
3247         .map            = intel_iommu_map_range,
3248         .unmap          = intel_iommu_unmap_range,
3249         .iova_to_phys   = intel_iommu_iova_to_phys,
3250         .domain_has_cap = intel_iommu_domain_has_cap,
3251 };
3252
3253 static void __devinit quirk_iommu_rwbf(struct pci_dev *dev)
3254 {
3255         /*
3256          * Mobile 4 Series Chipset neglects to set RWBF capability,
3257          * but needs it:
3258          */
3259         printk(KERN_INFO "DMAR: Forcing write-buffer flush capability\n");
3260         rwbf_quirk = 1;
3261 }
3262
3263 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_INTEL, 0x2a40, quirk_iommu_rwbf);