clocks: tegra12: Use static CPU-EMC co-relation
[linux-3.10.git] / drivers / iommu / arm-smmu.c
1 /*
2  * IOMMU API for ARM architected SMMU implementations.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, write to the Free Software
15  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
16  *
17  * Copyright (C) 2013 ARM Limited
18  *
19  * Author: Will Deacon <will.deacon@arm.com>
20  *
21  * This driver currently supports:
22  *      - SMMUv1 and v2 implementations
23  *      - Stream-matching and stream-indexing
24  *      - v7/v8 long-descriptor format
25  *      - Non-secure access to the SMMU
26  *      - 4k and 64k pages, with contiguous pte hints.
27  *      - Up to 48-bit addressing (dependent on VA_BITS)
28  *      - Context fault reporting
29  */
30
31 #define pr_fmt(fmt) "arm-smmu: " fmt
32
33 #include <linux/delay.h>
34 #include <linux/dma-mapping.h>
35 #include <linux/err.h>
36 #include <linux/interrupt.h>
37 #include <linux/io.h>
38 #include <linux/iommu.h>
39 #include <linux/mm.h>
40 #include <linux/module.h>
41 #include <linux/of.h>
42 #include <linux/pci.h>
43 #include <linux/platform_device.h>
44 #include <linux/slab.h>
45 #include <linux/spinlock.h>
46 #include <linux/debugfs.h>
47 #include <linux/uaccess.h>
48 #include <linux/dma-attrs.h>
49 #include <linux/tegra-soc.h>
50
51 #include <linux/amba/bus.h>
52
53 #include <dt-bindings/memory/tegra-swgroup.h>
54
55 #include <asm/pgalloc.h>
56 #include <asm/dma-iommu.h>
57 #include <asm/pgtable.h>
58
59 #define CREATE_TRACE_POINTS
60 #include <trace/events/arm_smmu.h>
61
62 #include "of_tegra-smmu.h" /* FIXME: to parse implicitly */
63 #include "tegra-smmu.h"
64
65 /* Maximum number of stream IDs assigned to a single device */
66 #define MAX_MASTER_STREAMIDS            MAX_PHANDLE_ARGS
67
68 /* Maximum number of context banks per SMMU */
69 #define ARM_SMMU_MAX_CBS                128
70
71 /* Maximum number of mapping groups per SMMU */
72 #define ARM_SMMU_MAX_SMRS               128
73
74 /* SMMU global address space */
75 #define ARM_SMMU_GR0(smmu)              ((smmu)->base)
76 #define ARM_SMMU_GR1(smmu)              ((smmu)->base + (1 << (smmu)->pgshift))
77 #define ARM_SMMU_PME(smmu)              ((smmu)->base + (3 << (smmu)->pgshift))
78
79 /*
80  * SMMU global address space with conditional offset to access secure
81  * aliases of non-secure registers (e.g. nsCR0: 0x400, nsGFSR: 0x448,
82  * nsGFSYNR0: 0x450)
83  */
84 #define ARM_SMMU_GR0_NS(smmu)                                           \
85         ((smmu)->base +                                                 \
86                 ((smmu->options & ARM_SMMU_OPT_SECURE_CFG_ACCESS)       \
87                         ? 0x400 : 0))
88
89 /* Page table bits */
90 #define ARM_SMMU_PTE_XN                 (((pteval_t)3) << 53)
91 #define ARM_SMMU_PTE_CONT               (((pteval_t)1) << 52)
92 #define ARM_SMMU_PTE_AF                 (((pteval_t)1) << 10)
93 #define ARM_SMMU_PTE_SH_NS              (((pteval_t)0) << 8)
94 #define ARM_SMMU_PTE_SH_OS              (((pteval_t)2) << 8)
95 #define ARM_SMMU_PTE_SH_IS              (((pteval_t)3) << 8)
96 #define ARM_SMMU_PTE_PAGE               (((pteval_t)3) << 0)
97
98 #if PAGE_SIZE == SZ_4K
99 #define ARM_SMMU_PTE_CONT_ENTRIES       16
100 #elif PAGE_SIZE == SZ_64K
101 #define ARM_SMMU_PTE_CONT_ENTRIES       32
102 #else
103 #define ARM_SMMU_PTE_CONT_ENTRIES       1
104 #endif
105
106 #define ARM_SMMU_PTE_CONT_SIZE          (PAGE_SIZE * ARM_SMMU_PTE_CONT_ENTRIES)
107 #define ARM_SMMU_PTE_CONT_MASK          (~(ARM_SMMU_PTE_CONT_SIZE - 1))
108
109 /* Stage-1 PTE */
110 #define ARM_SMMU_PTE_AP_UNPRIV          (((pteval_t)1) << 6)
111 #define ARM_SMMU_PTE_AP_RDONLY          (((pteval_t)2) << 6)
112 #define ARM_SMMU_PTE_ATTRINDX_SHIFT     2
113 #define ARM_SMMU_PTE_nG                 (((pteval_t)1) << 11)
114
115 /* Stage-2 PTE */
116 #define ARM_SMMU_PTE_HAP_FAULT          (((pteval_t)0) << 6)
117 #define ARM_SMMU_PTE_HAP_READ           (((pteval_t)1) << 6)
118 #define ARM_SMMU_PTE_HAP_WRITE          (((pteval_t)2) << 6)
119 #define ARM_SMMU_PTE_MEMATTR_OIWB       (((pteval_t)0xf) << 2)
120 #define ARM_SMMU_PTE_MEMATTR_NC         (((pteval_t)0x5) << 2)
121 #define ARM_SMMU_PTE_MEMATTR_DEV        (((pteval_t)0x1) << 2)
122
123 /* Configuration registers */
124 #define ARM_SMMU_GR0_sCR0               0x0
125 #define sCR0_CLIENTPD                   (1 << 0)
126 #define sCR0_GFRE                       (1 << 1)
127 #define sCR0_GFIE                       (1 << 2)
128 #define sCR0_GCFGFRE                    (1 << 4)
129 #define sCR0_GCFGFIE                    (1 << 5)
130 #define sCR0_USFCFG                     (1 << 10)
131 #define sCR0_VMIDPNE                    (1 << 11)
132 #define sCR0_PTM                        (1 << 12)
133 #define sCR0_FB                         (1 << 13)
134 #define sCR0_BSU_SHIFT                  14
135 #define sCR0_BSU_MASK                   0x3
136
137 /* Identification registers */
138 #define ARM_SMMU_GR0_ID0                0x20
139 #define ARM_SMMU_GR0_ID1                0x24
140 #define ARM_SMMU_GR0_ID2                0x28
141 #define ARM_SMMU_GR0_ID3                0x2c
142 #define ARM_SMMU_GR0_ID4                0x30
143 #define ARM_SMMU_GR0_ID5                0x34
144 #define ARM_SMMU_GR0_ID6                0x38
145 #define ARM_SMMU_GR0_ID7                0x3c
146 #define ARM_SMMU_GR0_sGFSR              0x48
147 #define ARM_SMMU_GR0_sGFSYNR0           0x50
148 #define ARM_SMMU_GR0_sGFSYNR1           0x54
149 #define ARM_SMMU_GR0_sGFSYNR2           0x58
150 #define ARM_SMMU_GR0_PIDR0              0xfe0
151 #define ARM_SMMU_GR0_PIDR1              0xfe4
152 #define ARM_SMMU_GR0_PIDR2              0xfe8
153
154 #define ID0_S1TS                        (1 << 30)
155 #define ID0_S2TS                        (1 << 29)
156 #define ID0_NTS                         (1 << 28)
157 #define ID0_SMS                         (1 << 27)
158 #define ID0_PTFS_SHIFT                  24
159 #define ID0_PTFS_MASK                   0x2
160 #define ID0_PTFS_V8_ONLY                0x2
161 #define ID0_CTTW                        (1 << 14)
162 #define ID0_NUMIRPT_SHIFT               16
163 #define ID0_NUMIRPT_MASK                0xff
164 #define ID0_NUMSIDB_SHIFT               9
165 #define ID0_NUMSIDB_MASK                0xf
166 #define ID0_NUMSMRG_SHIFT               0
167 #define ID0_NUMSMRG_MASK                0xff
168
169 #define ID1_PAGESIZE                    (1 << 31)
170 #define ID1_NUMPAGENDXB_SHIFT           28
171 #define ID1_NUMPAGENDXB_MASK            7
172 #define ID1_NUMS2CB_SHIFT               16
173 #define ID1_NUMS2CB_MASK                0xff
174 #define ID1_NUMCB_SHIFT                 0
175 #define ID1_NUMCB_MASK                  0xff
176
177 #define ID2_OAS_SHIFT                   4
178 #define ID2_OAS_MASK                    0xf
179 #define ID2_IAS_SHIFT                   0
180 #define ID2_IAS_MASK                    0xf
181 #define ID2_UBS_SHIFT                   8
182 #define ID2_UBS_MASK                    0xf
183 #define ID2_PTFS_4K                     (1 << 12)
184 #define ID2_PTFS_16K                    (1 << 13)
185 #define ID2_PTFS_64K                    (1 << 14)
186
187 #define PIDR2_ARCH_SHIFT                4
188 #define PIDR2_ARCH_MASK                 0xf
189
190 /* Global TLB invalidation */
191 #define ARM_SMMU_GR0_STLBIALL           0x60
192 #define ARM_SMMU_GR0_TLBIVMID           0x64
193 #define ARM_SMMU_GR0_TLBIALLNSNH        0x68
194 #define ARM_SMMU_GR0_TLBIALLH           0x6c
195 #define ARM_SMMU_GR0_sTLBGSYNC          0x70
196 #define ARM_SMMU_GR0_sTLBGSTATUS        0x74
197 #define sTLBGSTATUS_GSACTIVE            (1 << 0)
198 #define TLB_LOOP_TIMEOUT                1000000 /* 1s! */
199
200 /* Stream mapping registers */
201 #define ARM_SMMU_GR0_SMR(n)             (0x800 + ((n) << 2))
202 #define SMR_VALID                       (1 << 31)
203 #define SMR_MASK_SHIFT                  16
204 #define SMR_MASK_MASK                   0x7f80
205 #define SMR_ID_SHIFT                    0
206 #define SMR_ID_MASK                     0x7f80
207
208 #define ARM_SMMU_GR0_S2CR(n)            (0xc00 + ((n) << 2))
209 #define S2CR_CBNDX_SHIFT                0
210 #define S2CR_CBNDX_MASK                 0xff
211 #define S2CR_TYPE_SHIFT                 16
212 #define S2CR_TYPE_MASK                  0x3
213 #define S2CR_TYPE_TRANS                 (0 << S2CR_TYPE_SHIFT)
214 #define S2CR_TYPE_BYPASS                (1 << S2CR_TYPE_SHIFT)
215 #define S2CR_TYPE_FAULT                 (2 << S2CR_TYPE_SHIFT)
216
217 /* Context bank attribute registers */
218 #define ARM_SMMU_GR1_CBAR(n)            (0x0 + ((n) << 2))
219 #define CBAR_VMID_SHIFT                 0
220 #define CBAR_VMID_MASK                  0xff
221 #define CBAR_S1_BPSHCFG_SHIFT           8
222 #define CBAR_S1_BPSHCFG_MASK            3
223 #define CBAR_S1_BPSHCFG_NSH             3
224 #define CBAR_S1_MEMATTR_SHIFT           12
225 #define CBAR_S1_MEMATTR_MASK            0xf
226 #define CBAR_S1_MEMATTR_WB              0xf
227 #define CBAR_TYPE_SHIFT                 16
228 #define CBAR_TYPE_MASK                  0x3
229 #define CBAR_TYPE_S2_TRANS              (0 << CBAR_TYPE_SHIFT)
230 #define CBAR_TYPE_S1_TRANS_S2_BYPASS    (1 << CBAR_TYPE_SHIFT)
231 #define CBAR_TYPE_S1_TRANS_S2_FAULT     (2 << CBAR_TYPE_SHIFT)
232 #define CBAR_TYPE_S1_TRANS_S2_TRANS     (3 << CBAR_TYPE_SHIFT)
233 #define CBAR_IRPTNDX_SHIFT              24
234 #define CBAR_IRPTNDX_MASK               0xff
235
236 #define ARM_SMMU_GR1_CBA2R(n)           (0x800 + ((n) << 2))
237 #define CBA2R_RW64_32BIT                (0 << 0)
238 #define CBA2R_RW64_64BIT                (1 << 0)
239
240 /* Translation context bank */
241 #define ARM_SMMU_CB_BASE(smmu)          ((smmu)->base + ((smmu)->size >> 1))
242 #define ARM_SMMU_CB(smmu, n)            ((n) * (1 << (smmu)->pgshift))
243
244 #define ARM_SMMU_CB_SCTLR               0x0
245 #define ARM_SMMU_CB_RESUME              0x8
246 #define ARM_SMMU_CB_TTBCR2              0x10
247 #define ARM_SMMU_CB_TTBR0_LO            0x20
248 #define ARM_SMMU_CB_TTBR0_HI            0x24
249 #define ARM_SMMU_CB_TTBCR               0x30
250 #define ARM_SMMU_CB_S1_MAIR0            0x38
251 #define ARM_SMMU_CB_FSR                 0x58
252 #define ARM_SMMU_CB_FAR_LO              0x60
253 #define ARM_SMMU_CB_FAR_HI              0x64
254 #define ARM_SMMU_CB_FSYNR0              0x68
255 #define ARM_SMMU_CB_S1_TLBIASID         0x610
256
257 #define SCTLR_S1_ASIDPNE                (1 << 12)
258 #define SCTLR_CFCFG                     (1 << 7)
259 #define SCTLR_CFIE                      (1 << 6)
260 #define SCTLR_CFRE                      (1 << 5)
261 #define SCTLR_E                         (1 << 4)
262 #define SCTLR_AFE                       (1 << 2)
263 #define SCTLR_TRE                       (1 << 1)
264 #define SCTLR_M                         (1 << 0)
265 #define SCTLR_EAE_SBOP                  (SCTLR_AFE | SCTLR_TRE)
266
267 #define RESUME_RETRY                    (0 << 0)
268 #define RESUME_TERMINATE                (1 << 0)
269
270 #define TTBCR_EAE                       (1 << 31)
271
272 #define TTBCR_PASIZE_SHIFT              16
273 #define TTBCR_PASIZE_MASK               0x7
274
275 #define TTBCR_TG0_4K                    (0 << 14)
276 #define TTBCR_TG0_64K                   (1 << 14)
277
278 #define TTBCR_SH0_SHIFT                 12
279 #define TTBCR_SH0_MASK                  0x3
280 #define TTBCR_SH_NS                     0
281 #define TTBCR_SH_OS                     2
282 #define TTBCR_SH_IS                     3
283
284 #define TTBCR_ORGN0_SHIFT               10
285 #define TTBCR_IRGN0_SHIFT               8
286 #define TTBCR_RGN_MASK                  0x3
287 #define TTBCR_RGN_NC                    0
288 #define TTBCR_RGN_WBWA                  1
289 #define TTBCR_RGN_WT                    2
290 #define TTBCR_RGN_WB                    3
291
292 #define TTBCR_SL0_SHIFT                 6
293 #define TTBCR_SL0_MASK                  0x3
294 #define TTBCR_SL0_LVL_2                 0
295 #define TTBCR_SL0_LVL_1                 1
296
297 #define TTBCR_T1SZ_SHIFT                16
298 #define TTBCR_T0SZ_SHIFT                0
299 #define TTBCR_SZ_MASK                   0xf
300
301 #define TTBCR2_SEP_SHIFT                15
302 #define TTBCR2_SEP_MASK                 0x7
303
304 #define TTBCR2_PASIZE_SHIFT             0
305 #define TTBCR2_PASIZE_MASK              0x7
306
307 /* Common definitions for PASize and SEP fields */
308 #define TTBCR2_ADDR_32                  0
309 #define TTBCR2_ADDR_36                  1
310 #define TTBCR2_ADDR_40                  2
311 #define TTBCR2_ADDR_42                  3
312 #define TTBCR2_ADDR_44                  4
313 #define TTBCR2_ADDR_48                  5
314
315 #define TTBRn_HI_ASID_SHIFT             16
316
317 #define MAIR_ATTR_SHIFT(n)              ((n) << 3)
318 #define MAIR_ATTR_MASK                  0xff
319 #define MAIR_ATTR_DEVICE                0x04
320 #define MAIR_ATTR_NC                    0x44
321 #define MAIR_ATTR_WBRWA                 0xff
322 #define MAIR_ATTR_IDX_NC                0
323 #define MAIR_ATTR_IDX_CACHE             1
324 #define MAIR_ATTR_IDX_DEV               2
325
326 #define FSR_MULTI                       (1 << 31)
327 #define FSR_SS                          (1 << 30)
328 #define FSR_UUT                         (1 << 8)
329 #define FSR_ASF                         (1 << 7)
330 #define FSR_TLBLKF                      (1 << 6)
331 #define FSR_TLBMCF                      (1 << 5)
332 #define FSR_EF                          (1 << 4)
333 #define FSR_PF                          (1 << 3)
334 #define FSR_AFF                         (1 << 2)
335 #define FSR_TF                          (1 << 1)
336
337 #define FSR_IGN                         (FSR_AFF | FSR_ASF | \
338                                          FSR_TLBMCF | FSR_TLBLKF)
339 #define FSR_FAULT                       (FSR_MULTI | FSR_SS | FSR_UUT | \
340                                          FSR_EF | FSR_PF | FSR_TF | FSR_IGN)
341
342 #define FSYNR0_WNR                      (1 << 4)
343
344 #define NUM_SID                         64
345
346 static int force_stage;
347 module_param_named(force_stage, force_stage, int, S_IRUGO | S_IWUSR);
348 MODULE_PARM_DESC(force_stage,
349         "Force SMMU mappings to be installed at a particular stage of translation. A value of '1' or '2' forces the corresponding stage. All other values are ignored (i.e. no stage is forced). Note that selecting a specific stage will disable support for nested translation.");
350
351 enum arm_smmu_arch_version {
352         ARM_SMMU_V1 = 1,
353         ARM_SMMU_V2,
354 };
355
356 struct arm_smmu_smr {
357         u8                              idx;
358         u16                             mask;
359         u16                             id;
360 };
361
362 struct arm_smmu_master_cfg {
363         int                             num_streamids;
364         u16                             streamids[MAX_MASTER_STREAMIDS];
365         struct arm_smmu_smr             *smrs;
366
367         struct dentry                   *debugfs_root;
368 };
369
370 struct arm_smmu_master {
371         struct device_node              *of_node;
372         struct rb_node                  node;
373         struct arm_smmu_master_cfg      cfg;
374         struct dentry                   *debugfs_root;
375 };
376
377 struct arm_smmu_device {
378         struct device                   *dev;
379
380         void __iomem                    *base;
381         unsigned long                   size;
382         unsigned long                   pgshift;
383
384 #define ARM_SMMU_FEAT_COHERENT_WALK     (1 << 0)
385 #define ARM_SMMU_FEAT_STREAM_MATCH      (1 << 1)
386 #define ARM_SMMU_FEAT_TRANS_S1          (1 << 2)
387 #define ARM_SMMU_FEAT_TRANS_S2          (1 << 3)
388 #define ARM_SMMU_FEAT_TRANS_NESTED      (1 << 4)
389         u32                             features;
390
391 #define ARM_SMMU_OPT_SECURE_CFG_ACCESS (1 << 0)
392 #define ARM_SMMU_OPT_BROKEN_SIM_IRQ    (1 << 1)
393         u32                             options;
394         enum arm_smmu_arch_version      version;
395
396         u32                             num_context_banks;
397         u32                             num_s2_context_banks;
398         DECLARE_BITMAP(context_map, ARM_SMMU_MAX_CBS);
399         atomic_t                        irptndx;
400
401         u32                             num_mapping_groups;
402         DECLARE_BITMAP(smr_map, ARM_SMMU_MAX_SMRS);
403
404         unsigned long                   s1_input_size;
405         unsigned long                   s1_output_size;
406         unsigned long                   s2_input_size;
407         unsigned long                   s2_output_size;
408
409         u32                             num_global_irqs;
410         u32                             num_context_irqs;
411         unsigned int                    *irqs;
412
413         struct list_head                list;
414         struct rb_root                  masters;
415         struct dentry                   *masters_root;
416
417         struct dentry                   *debugfs_root;
418         struct debugfs_regset32         *regset;
419         DECLARE_BITMAP(context_filter, ARM_SMMU_MAX_CBS);
420
421         struct list_head                asprops;
422 };
423
424 struct arm_smmu_cfg {
425         u8                              cbndx;
426         u8                              irptndx;
427         u32                             cbar;
428         pgd_t                           *pgd;
429 };
430 #define INVALID_IRPTNDX                 0xff
431
432 #define ARM_SMMU_CB_ASID(cfg)           ((cfg)->cbndx)
433 #define ARM_SMMU_CB_VMID(cfg)           ((cfg)->cbndx + 1)
434
435 struct arm_smmu_domain {
436         struct arm_smmu_device          *smmu;
437         struct arm_smmu_cfg             cfg;
438         struct page *arm_dummy_page;   /* dummy page for faulted address*/
439         spinlock_t                      lock;
440
441         dma_addr_t                      inquired_iova;
442         phys_addr_t                     inquired_phys;
443 };
444
445 static struct iommu_domain *iommu_domains[NUM_SID]; /* To keep all allocated domains */
446 static struct arm_smmu_master_cfg *arm_smmu_master_cfgs[NUM_SID];
447
448 static DEFINE_SPINLOCK(arm_smmu_devices_lock);
449 static LIST_HEAD(arm_smmu_devices);
450
451 static struct arm_smmu_device *smmu_handle; /* assmu only one smmu device */
452 static u32 arm_smmu_skip_mapping; /* For debug */
453 static u32 arm_smmu_gr0_tlbiallnsnh; /* Insert TLBIALLNSNH at all */
454
455 #ifdef CONFIG_ARM_SMMU_WAR
456 /*
457  * linsim hacks: Indirect register accessor
458  */
459 #undef readl_relaxed
460 #undef writel_relaxed
461 #undef writel
462 #define __readl_relaxed(c)                                              \
463         ({ u32 __v = le32_to_cpu((__force __le32)__raw_readl(c)); __v; })
464 #define __writel(v,c)                                                   \
465         ({ __iowmb(); ((void)__raw_writel((__force u32)cpu_to_le32(v),(c))); })
466
467 static volatile void __iomem *mc_base;
468
469 #define MC_BASE                         0x22c10000 /* HACK: for c-model */
470 #define MC_SIZE                         0x00010000
471 #define ARM_SMMU_CONTROL_ADDRESS        0x24
472 #define ARM_SMMU_CONTROL_DATA           0x28
473
474 static inline void writel(u32 val, volatile void __iomem *virt_addr)
475 {
476         u32 offset;
477         volatile void __iomem *ctl_addr;
478
479         if (!tegra_platform_is_linsim()) {
480                 __writel(val, virt_addr);
481                 return;
482         }
483
484         ctl_addr = mc_base + ARM_SMMU_CONTROL_ADDRESS;
485         offset = virt_addr - smmu_handle->base;
486         __writel(offset, ctl_addr);
487         pr_debug("Indirect write(ADDRESS) offset=%08x ctl_addr=%p\n",
488                  offset, ctl_addr);
489
490         ctl_addr = mc_base + ARM_SMMU_CONTROL_DATA;
491         __writel(val, ctl_addr);
492         pr_debug("Indirect write(DATA) val=%08x ctl_addr=%p\n", val, ctl_addr);
493 }
494 #define writel_relaxed(v,a) writel(v,a)
495
496 static inline u32 readl_relaxed(const volatile void __iomem *virt_addr)
497 {
498         u32 val, offset;
499         volatile void __iomem *ctl_addr;
500
501         if (!tegra_platform_is_linsim())
502                 return __readl_relaxed(virt_addr);
503
504         ctl_addr = mc_base + ARM_SMMU_CONTROL_ADDRESS;
505         offset = virt_addr - smmu_handle->base;
506         __writel(offset, ctl_addr);
507         pr_debug("Indirect read(ADDRESS) offset=%08x ctl_addr=%p\n",
508                  offset, ctl_addr);
509
510         ctl_addr = mc_base + ARM_SMMU_CONTROL_DATA;
511         val = __readl_relaxed(ctl_addr);
512         pr_debug("Indirect read(DATA) val=%08x ctl_addr=%p\n", val, ctl_addr);
513         return val;
514 }
515 #endif
516
517 void __weak platform_override_streamid(int streamid)
518 {
519 }
520
521 static phys_addr_t arm_smmu_iova_to_phys(struct iommu_domain *domain,
522                                         dma_addr_t iova);
523
524 struct arm_smmu_option_prop {
525         u32 opt;
526         const char *prop;
527 };
528
529 static struct arm_smmu_option_prop arm_smmu_options[] = {
530         { ARM_SMMU_OPT_SECURE_CFG_ACCESS, "calxeda,smmu-secure-config-access" },
531         { ARM_SMMU_OPT_SECURE_CFG_ACCESS, "-calxeda,smmu-secure-config-access" },
532         { ARM_SMMU_OPT_BROKEN_SIM_IRQ, "linsim,smmu-broken-sim-irq" },
533         { 0, NULL},
534 };
535
536 static void parse_driver_options(struct arm_smmu_device *smmu)
537 {
538         int i = 0;
539
540         do {
541                 if (of_property_read_bool(smmu->dev->of_node,
542                                                 arm_smmu_options[i].prop)) {
543                         if (arm_smmu_options[i].prop[0] == '-')
544                                 smmu->options &= ~arm_smmu_options[i].opt;
545                         else
546                                 smmu->options |= arm_smmu_options[i].opt;
547                         dev_notice(smmu->dev, "option %s\n",
548                                 arm_smmu_options[i].prop);
549                 }
550         } while (arm_smmu_options[++i].opt);
551 }
552
553 static struct device_node *dev_get_dev_node(struct device *dev)
554 {
555         if (dev_is_pci(dev)) {
556                 struct pci_bus *bus = to_pci_dev(dev)->bus;
557
558                 while (!pci_is_root_bus(bus))
559                         bus = bus->parent;
560                 return bus->bridge->parent->of_node;
561         }
562
563         return dev->of_node;
564 }
565
566 static struct arm_smmu_master *find_smmu_master(struct arm_smmu_device *smmu,
567                                                 struct device_node *dev_node)
568 {
569         struct rb_node *node = smmu->masters.rb_node;
570
571         while (node) {
572                 struct arm_smmu_master *master;
573
574                 master = container_of(node, struct arm_smmu_master, node);
575
576                 if (dev_node < master->of_node)
577                         node = node->rb_left;
578                 else if (dev_node > master->of_node)
579                         node = node->rb_right;
580                 else
581                         return master;
582         }
583
584         return NULL;
585 }
586
587 static struct arm_smmu_master_cfg *
588 find_smmu_master_cfg(struct device *dev)
589 {
590         struct arm_smmu_master_cfg *cfg = NULL;
591         struct iommu_group *group = iommu_group_get(dev);
592
593         if (group) {
594                 cfg = iommu_group_get_iommudata(group);
595                 iommu_group_put(group);
596         }
597
598         return cfg;
599 }
600
601 static int insert_smmu_master(struct arm_smmu_device *smmu,
602                               struct arm_smmu_master *master)
603 {
604         struct rb_node **new, *parent;
605
606         new = &smmu->masters.rb_node;
607         parent = NULL;
608         while (*new) {
609                 struct arm_smmu_master *this
610                         = container_of(*new, struct arm_smmu_master, node);
611
612                 parent = *new;
613                 if (master->of_node < this->of_node)
614                         new = &((*new)->rb_left);
615                 else if (master->of_node > this->of_node)
616                         new = &((*new)->rb_right);
617                 else
618                         return -EEXIST;
619         }
620
621         rb_link_node(&master->node, parent, new);
622         rb_insert_color(&master->node, &smmu->masters);
623         return 0;
624 }
625
626 static int register_smmu_master(struct arm_smmu_device *smmu,
627                                 struct device *dev,
628                                 struct of_phandle_args *masterspec)
629 {
630         int i;
631         struct arm_smmu_master *master;
632
633         master = find_smmu_master(smmu, masterspec->np);
634         if (master) {
635                 dev_err(dev,
636                         "rejecting multiple registrations for master device %s\n",
637                         masterspec->np->name);
638                 return -EBUSY;
639         }
640
641         if (masterspec->args_count > MAX_MASTER_STREAMIDS) {
642                 dev_err(dev,
643                         "reached maximum number (%d) of stream IDs for master device %s\n",
644                         MAX_MASTER_STREAMIDS, masterspec->np->name);
645                 return -ENOSPC;
646         }
647
648         master = devm_kzalloc(dev, sizeof(*master), GFP_KERNEL);
649         if (!master)
650                 return -ENOMEM;
651
652         master->of_node                 = masterspec->np;
653         master->cfg.num_streamids       = masterspec->args_count;
654
655         for (i = 0; i < master->cfg.num_streamids; ++i) {
656                 u16 streamid = masterspec->args[i];
657
658                 if (!(smmu->features & ARM_SMMU_FEAT_STREAM_MATCH) &&
659                      (streamid >= smmu->num_mapping_groups)) {
660                         dev_err(dev,
661                                 "stream ID for master device %s greater than maximum allowed (%d)\n",
662                                 masterspec->np->name, smmu->num_mapping_groups);
663                         return -ERANGE;
664                 }
665                 master->cfg.streamids[i] = streamid;
666                 platform_override_streamid(streamid);
667                 if (!arm_smmu_master_cfgs[streamid]) {
668                         arm_smmu_master_cfgs[streamid] = &master->cfg;
669                         dev_dbg(dev, "%s() streamid=%x sets cfg=%p\n",
670                                 __func__, streamid, &master->cfg);
671                 }
672         }
673         return insert_smmu_master(smmu, master);
674 }
675
676 static struct arm_smmu_device *find_smmu_for_device(struct device *dev)
677 {
678         struct arm_smmu_device *smmu;
679         struct arm_smmu_master *master = NULL;
680         struct device_node *dev_node = dev_get_dev_node(dev);
681
682         spin_lock(&arm_smmu_devices_lock);
683         list_for_each_entry(smmu, &arm_smmu_devices, list) {
684                 master = find_smmu_master(smmu, dev_node);
685                 if (master)
686                         break;
687         }
688         spin_unlock(&arm_smmu_devices_lock);
689
690         return master ? smmu : NULL;
691 }
692
693 static int __arm_smmu_alloc_bitmap(unsigned long *map, int start, int end)
694 {
695         int idx;
696
697         do {
698                 idx = find_next_zero_bit(map, end, start);
699                 if (idx == end)
700                         return -ENOSPC;
701         } while (test_and_set_bit(idx, map));
702
703         return idx;
704 }
705
706 static void __arm_smmu_free_bitmap(unsigned long *map, int idx)
707 {
708         clear_bit(idx, map);
709 }
710
711 /* Wait for any pending TLB invalidations to complete */
712 static void arm_smmu_tlb_sync(struct arm_smmu_device *smmu)
713 {
714         int count = 0;
715         void __iomem *gr0_base = ARM_SMMU_GR0(smmu);
716
717         if (tegra_platform_is_linsim() || arm_smmu_gr0_tlbiallnsnh)
718                 writel_relaxed(0, gr0_base + ARM_SMMU_GR0_TLBIALLNSNH);
719
720         writel_relaxed(0, gr0_base + ARM_SMMU_GR0_sTLBGSYNC);
721         while (readl_relaxed(gr0_base + ARM_SMMU_GR0_sTLBGSTATUS)
722                & sTLBGSTATUS_GSACTIVE) {
723                 cpu_relax();
724                 if (++count == TLB_LOOP_TIMEOUT) {
725                         dev_err_ratelimited(smmu->dev,
726                         "TLB sync timed out -- SMMU may be deadlocked\n");
727                         return;
728                 }
729                 udelay(1);
730         }
731 }
732
733 static void arm_smmu_tlb_inv_context(struct arm_smmu_domain *smmu_domain)
734 {
735         struct arm_smmu_cfg *cfg = &smmu_domain->cfg;
736         struct arm_smmu_device *smmu = smmu_domain->smmu;
737         void __iomem *base = ARM_SMMU_GR0(smmu);
738         bool stage1 = cfg->cbar != CBAR_TYPE_S2_TRANS;
739
740         if (stage1) {
741                 base = ARM_SMMU_CB_BASE(smmu) + ARM_SMMU_CB(smmu, cfg->cbndx);
742                 writel_relaxed(ARM_SMMU_CB_ASID(cfg),
743                                base + ARM_SMMU_CB_S1_TLBIASID);
744         } else {
745                 base = ARM_SMMU_GR0(smmu);
746                 writel_relaxed(ARM_SMMU_CB_VMID(cfg),
747                                base + ARM_SMMU_GR0_TLBIVMID);
748         }
749
750         arm_smmu_tlb_sync(smmu);
751 }
752
753 static irqreturn_t __arm_smmu_context_fault(int irq, void *dev)
754 {
755         int flags, ret;
756         u32 fsr, far, fsynr, resume;
757         unsigned long iova;
758         struct iommu_domain *domain = dev;
759         struct arm_smmu_domain *smmu_domain = domain->priv;
760         struct arm_smmu_cfg *cfg = &smmu_domain->cfg;
761         struct arm_smmu_device *smmu = smmu_domain->smmu;
762         void __iomem *cb_base;
763
764         cb_base = ARM_SMMU_CB_BASE(smmu) + ARM_SMMU_CB(smmu, cfg->cbndx);
765         fsr = readl_relaxed(cb_base + ARM_SMMU_CB_FSR);
766
767         if (!(fsr & FSR_FAULT))
768                 return IRQ_NONE;
769
770         if (fsr & FSR_IGN)
771                 dev_err_ratelimited(smmu->dev,
772                                     "Unexpected context fault (fsr 0x%x)\n",
773                                     fsr);
774
775         fsynr = readl_relaxed(cb_base + ARM_SMMU_CB_FSYNR0);
776         flags = fsynr & FSYNR0_WNR ? IOMMU_FAULT_WRITE : IOMMU_FAULT_READ;
777
778         far = readl_relaxed(cb_base + ARM_SMMU_CB_FAR_LO);
779         iova = far;
780 #ifdef CONFIG_64BIT
781         far = readl_relaxed(cb_base + ARM_SMMU_CB_FAR_HI);
782         iova |= ((unsigned long)far << 32);
783 #endif
784
785         if (!report_iommu_fault(domain, smmu->dev, iova, flags)) {
786                 ret = IRQ_HANDLED;
787                 resume = RESUME_RETRY;
788         } else {
789                 dev_err_ratelimited(smmu->dev,
790                     "Unhandled context fault: iova=0x%08lx, fsynr=0x%x, cb=%d\n",
791                     iova, fsynr, cfg->cbndx);
792                 ret = IRQ_NONE;
793                 resume = RESUME_TERMINATE;
794         }
795
796         /* Clear the faulting FSR */
797         writel(fsr, cb_base + ARM_SMMU_CB_FSR);
798
799         /* Retry or terminate any stalled transactions */
800         if (fsr & FSR_SS)
801                 writel_relaxed(resume, cb_base + ARM_SMMU_CB_RESUME);
802
803         return ret;
804 }
805
806 static irqreturn_t arm_smmu_context_fault(int irq, void *dev)
807 {
808         int i;
809         struct arm_smmu_device *smmu = dev;
810
811         for (i = 0; i < smmu->num_context_banks; i++) {
812                 void __iomem *cb_base;
813                 struct iommu_domain *domain;
814                 u32 fsr;
815
816                 cb_base = ARM_SMMU_CB_BASE(smmu) + ARM_SMMU_CB(smmu, i);
817                 fsr = readl_relaxed(cb_base + ARM_SMMU_CB_FSR);
818                 if (fsr & FSR_FAULT) {
819                         domain = iommu_domains[i];
820                         if (!domain) {
821                                 pr_err("domain(%d) doesn't exist\n", i);
822                                 continue;
823                         }
824                         return __arm_smmu_context_fault(irq, domain);
825                 }
826         }
827
828         pr_err("unexpected smmu error: neither global fault not context fault\n");
829         return IRQ_NONE;
830 }
831
832 static irqreturn_t arm_smmu_global_fault(int irq, void *dev)
833 {
834         u32 gfsr, gfsynr0, gfsynr1, gfsynr2;
835         struct arm_smmu_device *smmu = dev;
836         void __iomem *gr0_base = ARM_SMMU_GR0_NS(smmu);
837
838         gfsr = readl_relaxed(gr0_base + ARM_SMMU_GR0_sGFSR);
839         gfsynr0 = readl_relaxed(gr0_base + ARM_SMMU_GR0_sGFSYNR0);
840         gfsynr1 = readl_relaxed(gr0_base + ARM_SMMU_GR0_sGFSYNR1);
841         gfsynr2 = readl_relaxed(gr0_base + ARM_SMMU_GR0_sGFSYNR2);
842
843         if (!gfsr)
844                 return arm_smmu_context_fault(irq, dev);
845
846         dev_err_ratelimited(smmu->dev,
847                 "Unexpected global fault, this could be serious\n");
848         dev_err_ratelimited(smmu->dev,
849                 "\tGFSR 0x%08x, GFSYNR0 0x%08x, GFSYNR1 0x%08x, GFSYNR2 0x%08x\n",
850                 gfsr, gfsynr0, gfsynr1, gfsynr2);
851
852         writel(gfsr, gr0_base + ARM_SMMU_GR0_sGFSR);
853         return IRQ_HANDLED;
854 }
855
856 static void arm_smmu_flush_pgtable(struct arm_smmu_device *smmu, void *addr,
857                                    size_t size)
858 {
859         unsigned long offset = (unsigned long)addr & ~PAGE_MASK;
860
861
862         /* Ensure new page tables are visible to the hardware walker */
863         if (smmu->features & ARM_SMMU_FEAT_COHERENT_WALK) {
864                 dsb();
865         } else {
866                 /*
867                  * If the SMMU can't walk tables in the CPU caches, treat them
868                  * like non-coherent DMA since we need to flush the new entries
869                  * all the way out to memory. There's no possibility of
870                  * recursion here as the SMMU table walker will not be wired
871                  * through another SMMU.
872                  */
873                 dma_map_page(smmu->dev, virt_to_page(addr), offset, size,
874                                 DMA_TO_DEVICE);
875         }
876 }
877
878 static void arm_smmu_init_context_bank(struct arm_smmu_domain *smmu_domain)
879 {
880         u32 reg;
881         bool stage1;
882         struct arm_smmu_cfg *cfg = &smmu_domain->cfg;
883         struct arm_smmu_device *smmu = smmu_domain->smmu;
884         void __iomem *cb_base, *gr0_base, *gr1_base;
885
886         gr0_base = ARM_SMMU_GR0(smmu);
887         gr1_base = ARM_SMMU_GR1(smmu);
888         stage1 = cfg->cbar != CBAR_TYPE_S2_TRANS;
889         cb_base = ARM_SMMU_CB_BASE(smmu) + ARM_SMMU_CB(smmu, cfg->cbndx);
890
891         /* CBAR */
892         reg = cfg->cbar;
893         if (smmu->version == ARM_SMMU_V1)
894                 reg |= cfg->irptndx << CBAR_IRPTNDX_SHIFT;
895
896         /*
897          * Use the weakest shareability/memory types, so they are
898          * overridden by the ttbcr/pte.
899          */
900         if (stage1) {
901                 reg |= (CBAR_S1_BPSHCFG_NSH << CBAR_S1_BPSHCFG_SHIFT) |
902                         (CBAR_S1_MEMATTR_WB << CBAR_S1_MEMATTR_SHIFT);
903         } else {
904                 reg |= ARM_SMMU_CB_VMID(cfg) << CBAR_VMID_SHIFT;
905         }
906         writel_relaxed(reg, gr1_base + ARM_SMMU_GR1_CBAR(cfg->cbndx));
907
908         if (smmu->version > ARM_SMMU_V1) {
909                 /* CBA2R */
910 #ifdef CONFIG_64BIT
911                 reg = CBA2R_RW64_64BIT;
912 #else
913                 reg = CBA2R_RW64_32BIT;
914 #endif
915                 writel_relaxed(reg,
916                                gr1_base + ARM_SMMU_GR1_CBA2R(cfg->cbndx));
917
918                 /* TTBCR2 */
919                 switch (smmu->s1_input_size) {
920                 case 32:
921                         reg = (TTBCR2_ADDR_32 << TTBCR2_SEP_SHIFT);
922                         break;
923                 case 36:
924                         reg = (TTBCR2_ADDR_36 << TTBCR2_SEP_SHIFT);
925                         break;
926                 case 39:
927                 case 40:
928                         reg = (TTBCR2_ADDR_40 << TTBCR2_SEP_SHIFT);
929                         break;
930                 case 42:
931                         reg = (TTBCR2_ADDR_42 << TTBCR2_SEP_SHIFT);
932                         break;
933                 case 44:
934                         reg = (TTBCR2_ADDR_44 << TTBCR2_SEP_SHIFT);
935                         break;
936                 case 48:
937                         reg = (TTBCR2_ADDR_48 << TTBCR2_SEP_SHIFT);
938                         break;
939                 }
940
941                 switch (smmu->s1_output_size) {
942                 case 32:
943                         reg |= (TTBCR2_ADDR_32 << TTBCR2_PASIZE_SHIFT);
944                         break;
945                 case 36:
946                         reg |= (TTBCR2_ADDR_36 << TTBCR2_PASIZE_SHIFT);
947                         break;
948                 case 39:
949                 case 40:
950                         reg |= (TTBCR2_ADDR_40 << TTBCR2_PASIZE_SHIFT);
951                         break;
952                 case 42:
953                         reg |= (TTBCR2_ADDR_42 << TTBCR2_PASIZE_SHIFT);
954                         break;
955                 case 44:
956                         reg |= (TTBCR2_ADDR_44 << TTBCR2_PASIZE_SHIFT);
957                         break;
958                 case 48:
959                         reg |= (TTBCR2_ADDR_48 << TTBCR2_PASIZE_SHIFT);
960                         break;
961                 }
962
963                 if (stage1)
964                         writel_relaxed(reg, cb_base + ARM_SMMU_CB_TTBCR2);
965         }
966
967         /* TTBR0 */
968         arm_smmu_flush_pgtable(smmu, cfg->pgd,
969                                PTRS_PER_PGD * sizeof(pgd_t));
970         reg = __pa(cfg->pgd);
971         writel_relaxed(reg, cb_base + ARM_SMMU_CB_TTBR0_LO);
972         reg = (phys_addr_t)__pa(cfg->pgd) >> 32;
973         if (stage1)
974                 reg |= ARM_SMMU_CB_ASID(cfg) << TTBRn_HI_ASID_SHIFT;
975         writel_relaxed(reg, cb_base + ARM_SMMU_CB_TTBR0_HI);
976
977         /*
978          * TTBCR
979          * We use long descriptor, with inner-shareable WBWA tables in TTBR0.
980          */
981         if (smmu->version > ARM_SMMU_V1) {
982                 if (PAGE_SIZE == SZ_4K)
983                         reg = TTBCR_TG0_4K;
984                 else
985                         reg = TTBCR_TG0_64K;
986
987                 if (!stage1) {
988                         reg |= (64 - smmu->s2_input_size) << TTBCR_T0SZ_SHIFT;
989
990                         switch (smmu->s2_output_size) {
991                         case 32:
992                                 reg |= (TTBCR2_ADDR_32 << TTBCR_PASIZE_SHIFT);
993                                 break;
994                         case 36:
995                                 reg |= (TTBCR2_ADDR_36 << TTBCR_PASIZE_SHIFT);
996                                 break;
997                         case 40:
998                                 reg |= (TTBCR2_ADDR_40 << TTBCR_PASIZE_SHIFT);
999                                 break;
1000                         case 42:
1001                                 reg |= (TTBCR2_ADDR_42 << TTBCR_PASIZE_SHIFT);
1002                                 break;
1003                         case 44:
1004                                 reg |= (TTBCR2_ADDR_44 << TTBCR_PASIZE_SHIFT);
1005                                 break;
1006                         case 48:
1007                                 reg |= (TTBCR2_ADDR_48 << TTBCR_PASIZE_SHIFT);
1008                                 break;
1009                         }
1010                 } else {
1011                         reg |= (64 - smmu->s1_input_size) << TTBCR_T0SZ_SHIFT;
1012                 }
1013         } else {
1014                 reg = 0;
1015         }
1016
1017         reg |= TTBCR_EAE |
1018               (TTBCR_SH_IS << TTBCR_SH0_SHIFT) |
1019               (TTBCR_RGN_WBWA << TTBCR_ORGN0_SHIFT) |
1020               (TTBCR_RGN_WBWA << TTBCR_IRGN0_SHIFT);
1021
1022         if (!stage1)
1023                 reg |= (TTBCR_SL0_LVL_1 << TTBCR_SL0_SHIFT);
1024
1025         writel_relaxed(reg, cb_base + ARM_SMMU_CB_TTBCR);
1026
1027         /* MAIR0 (stage-1 only) */
1028         if (stage1) {
1029                 reg = (MAIR_ATTR_NC << MAIR_ATTR_SHIFT(MAIR_ATTR_IDX_NC)) |
1030                       (MAIR_ATTR_WBRWA << MAIR_ATTR_SHIFT(MAIR_ATTR_IDX_CACHE)) |
1031                       (MAIR_ATTR_DEVICE << MAIR_ATTR_SHIFT(MAIR_ATTR_IDX_DEV));
1032                 writel_relaxed(reg, cb_base + ARM_SMMU_CB_S1_MAIR0);
1033         }
1034
1035         /* SCTLR */
1036         reg = SCTLR_CFIE | SCTLR_CFRE | SCTLR_M | SCTLR_EAE_SBOP;
1037         if (stage1)
1038                 reg |= SCTLR_S1_ASIDPNE;
1039 #ifdef __BIG_ENDIAN
1040         reg |= SCTLR_E;
1041 #endif
1042         writel_relaxed(reg, cb_base + ARM_SMMU_CB_SCTLR);
1043 }
1044
1045 static int arm_smmu_init_domain_context(struct iommu_domain *domain,
1046                                         struct arm_smmu_device *smmu)
1047 {
1048         int irq, start, ret = 0;
1049         unsigned long flags;
1050         struct arm_smmu_domain *smmu_domain = domain->priv;
1051         struct arm_smmu_cfg *cfg = &smmu_domain->cfg;
1052
1053         spin_lock_irqsave(&smmu_domain->lock, flags);
1054         if (smmu_domain->smmu)
1055                 goto out_unlock;
1056
1057         if (smmu->features & ARM_SMMU_FEAT_TRANS_NESTED) {
1058                 /*
1059                  * We will likely want to change this if/when KVM gets
1060                  * involved.
1061                  */
1062                 cfg->cbar = CBAR_TYPE_S1_TRANS_S2_BYPASS;
1063                 start = smmu->num_s2_context_banks;
1064         } else if (smmu->features & ARM_SMMU_FEAT_TRANS_S1) {
1065                 cfg->cbar = CBAR_TYPE_S1_TRANS_S2_BYPASS;
1066                 start = smmu->num_s2_context_banks;
1067         } else {
1068                 cfg->cbar = CBAR_TYPE_S2_TRANS;
1069                 start = 0;
1070         }
1071
1072         ret = __arm_smmu_alloc_bitmap(smmu->context_map, start,
1073                                       smmu->num_context_banks);
1074         if (IS_ERR_VALUE(ret))
1075                 goto out_unlock;
1076
1077         cfg->cbndx = ret;
1078         if (smmu->version == ARM_SMMU_V1) {
1079                 cfg->irptndx = atomic_inc_return(&smmu->irptndx);
1080                 cfg->irptndx %= smmu->num_context_irqs;
1081         } else if (smmu->num_context_banks == smmu->num_context_irqs) {
1082                 cfg->irptndx = cfg->cbndx;
1083         } else {
1084                 cfg->irptndx = 0;
1085         }
1086
1087         ACCESS_ONCE(smmu_domain->smmu) = smmu;
1088         arm_smmu_init_context_bank(smmu_domain);
1089         spin_unlock_irqrestore(&smmu_domain->lock, flags);
1090
1091         if (smmu->num_context_irqs) {
1092
1093                 irq = smmu->irqs[smmu->num_global_irqs + cfg->irptndx];
1094                 ret = request_irq(irq, arm_smmu_context_fault, IRQF_SHARED,
1095                           "arm-smmu-context-fault", domain);
1096                 if (IS_ERR_VALUE(ret)) {
1097                         dev_err(smmu->dev,
1098                                 "failed to request context IRQ %d (%u)\n",
1099                                 cfg->irptndx, irq);
1100                         cfg->irptndx = INVALID_IRPTNDX;
1101                 }
1102         }
1103
1104         BUG_ON(iommu_domains[cfg->cbndx]);
1105         iommu_domains[cfg->cbndx] = domain;
1106         return 0;
1107
1108 out_unlock:
1109         spin_unlock_irqrestore(&smmu_domain->lock, flags);
1110         return ret;
1111 }
1112
1113 static void arm_smmu_destroy_domain_context(struct iommu_domain *domain)
1114 {
1115         struct arm_smmu_domain *smmu_domain = domain->priv;
1116         struct arm_smmu_device *smmu = smmu_domain->smmu;
1117         struct arm_smmu_cfg *cfg = &smmu_domain->cfg;
1118         void __iomem *cb_base;
1119         int irq;
1120
1121         if (!smmu)
1122                 return;
1123
1124         /* Disable the context bank and nuke the TLB before freeing it. */
1125         cb_base = ARM_SMMU_CB_BASE(smmu) + ARM_SMMU_CB(smmu, cfg->cbndx);
1126         writel_relaxed(0, cb_base + ARM_SMMU_CB_SCTLR);
1127         arm_smmu_tlb_inv_context(smmu_domain);
1128
1129         if ((smmu->num_context_irqs) &&
1130                 (cfg->irptndx != INVALID_IRPTNDX)) {
1131                 irq = smmu->irqs[smmu->num_global_irqs + cfg->irptndx];
1132                 free_irq(irq, domain);
1133         }
1134
1135         __arm_smmu_free_bitmap(smmu->context_map, cfg->cbndx);
1136         iommu_domains[cfg->cbndx] = NULL;
1137 }
1138
1139 static int arm_smmu_get_hwid(struct iommu_domain *domain,
1140                              struct device *dev, unsigned int id)
1141 {
1142         struct arm_smmu_master_cfg *cfg;
1143
1144         cfg = find_smmu_master_cfg(dev);
1145         if (!cfg)
1146                 return -EINVAL;
1147
1148         if (id >= cfg->num_streamids)
1149                 return -EINVAL;
1150
1151         return cfg->streamids[id];
1152 }
1153
1154 static int arm_smmu_domain_init(struct iommu_domain *domain)
1155 {
1156         struct arm_smmu_domain *smmu_domain;
1157         pgd_t *pgd;
1158
1159         /*
1160          * Allocate the domain and initialise some of its data structures.
1161          * We can't really do anything meaningful until we've added a
1162          * master.
1163          */
1164         smmu_domain = kzalloc(sizeof(*smmu_domain), GFP_KERNEL);
1165         if (!smmu_domain)
1166                 return -ENOMEM;
1167
1168         pgd = kcalloc(PTRS_PER_PGD, sizeof(pgd_t), GFP_KERNEL);
1169         if (!pgd)
1170                 goto out_free_domain;
1171         smmu_domain->cfg.pgd = pgd;
1172
1173         spin_lock_init(&smmu_domain->lock);
1174
1175         smmu_domain->arm_dummy_page = alloc_page(GFP_KERNEL | __GFP_ZERO);
1176         if (!smmu_domain->arm_dummy_page)
1177                 return -ENOMEM;
1178
1179         domain->priv = smmu_domain;
1180         return 0;
1181
1182 out_free_domain:
1183         kfree(smmu_domain);
1184         return -ENOMEM;
1185 }
1186
1187 static void arm_smmu_free_ptes(pmd_t *pmd)
1188 {
1189         pgtable_t table = pmd_pgtable(*pmd);
1190
1191         __free_page(table);
1192 }
1193
1194 static void arm_smmu_free_pmds(pud_t *pud)
1195 {
1196         int i;
1197         pmd_t *pmd, *pmd_base = pmd_offset(pud, 0);
1198
1199         pmd = pmd_base;
1200         for (i = 0; i < PTRS_PER_PMD; ++i) {
1201                 if (pmd_none(*pmd))
1202                         continue;
1203
1204                 arm_smmu_free_ptes(pmd);
1205                 pmd++;
1206         }
1207
1208         pmd_free(NULL, pmd_base);
1209 }
1210
1211 static void arm_smmu_free_puds(pgd_t *pgd)
1212 {
1213         int i;
1214         pud_t *pud, *pud_base = pud_offset(pgd, 0);
1215
1216         pud = pud_base;
1217         for (i = 0; i < PTRS_PER_PUD; ++i) {
1218                 if (pud_none(*pud))
1219                         continue;
1220
1221                 arm_smmu_free_pmds(pud);
1222                 pud++;
1223         }
1224
1225         pud_free(NULL, pud_base);
1226 }
1227
1228 static void arm_smmu_free_pgtables(struct arm_smmu_domain *smmu_domain)
1229 {
1230         int i;
1231         struct arm_smmu_cfg *cfg = &smmu_domain->cfg;
1232         pgd_t *pgd, *pgd_base = cfg->pgd;
1233
1234         /*
1235          * Recursively free the page tables for this domain. We don't
1236          * care about speculative TLB filling because the tables should
1237          * not be active in any context bank at this point (SCTLR.M is 0).
1238          */
1239         pgd = pgd_base;
1240         for (i = 0; i < PTRS_PER_PGD; ++i) {
1241                 if (pgd_none(*pgd))
1242                         continue;
1243                 arm_smmu_free_puds(pgd);
1244                 pgd++;
1245         }
1246
1247         kfree(pgd_base);
1248 }
1249
1250 static void arm_smmu_domain_destroy(struct iommu_domain *domain)
1251 {
1252         struct arm_smmu_domain *smmu_domain = domain->priv;
1253
1254         /*
1255          * Free the domain resources. We assume that all devices have
1256          * already been detached.
1257          */
1258         arm_smmu_destroy_domain_context(domain);
1259         arm_smmu_free_pgtables(smmu_domain);
1260         __free_page(smmu_domain->arm_dummy_page);
1261         kfree(smmu_domain);
1262 }
1263
1264 static int arm_smmu_master_configure_smrs(struct arm_smmu_device *smmu,
1265                                           struct arm_smmu_master_cfg *cfg)
1266 {
1267         int i;
1268         struct arm_smmu_smr *smrs;
1269         void __iomem *gr0_base = ARM_SMMU_GR0(smmu);
1270
1271         if (!(smmu->features & ARM_SMMU_FEAT_STREAM_MATCH))
1272                 return 0;
1273
1274         if (cfg->smrs) {
1275                 pr_debug("%s() cfg->smrs=%p exists\n", __func__, cfg->smrs);
1276                 return -EEXIST;
1277         }
1278
1279         smrs = kmalloc_array(cfg->num_streamids, sizeof(*smrs), GFP_KERNEL);
1280         if (!smrs) {
1281                 dev_err(smmu->dev, "failed to allocate %d SMRs\n",
1282                         cfg->num_streamids);
1283                 return -ENOMEM;
1284         }
1285
1286         /* Allocate the SMRs on the SMMU */
1287         for (i = 0; i < cfg->num_streamids; ++i) {
1288                 int idx = __arm_smmu_alloc_bitmap(smmu->smr_map, 0,
1289                                                   smmu->num_mapping_groups);
1290                 if (IS_ERR_VALUE(idx)) {
1291                         dev_err(smmu->dev, "failed to allocate free SMR\n");
1292                         goto err_free_smrs;
1293                 }
1294
1295                 smrs[i] = (struct arm_smmu_smr) {
1296                         .idx    = idx,
1297                         .mask   = SMR_ID_MASK,
1298                         .id     = cfg->streamids[i],
1299                 };
1300         }
1301
1302         /* It worked! Now, poke the actual hardware */
1303         for (i = 0; i < cfg->num_streamids; ++i) {
1304                 u32 reg = SMR_VALID | smrs[i].id << SMR_ID_SHIFT |
1305                           smrs[i].mask << SMR_MASK_SHIFT;
1306                 writel_relaxed(reg, gr0_base + ARM_SMMU_GR0_SMR(smrs[i].idx));
1307         }
1308
1309         cfg->smrs = smrs;
1310         pr_debug("%s() set cfg->smrs=%p\n", __func__, cfg->smrs);
1311         return 0;
1312
1313 err_free_smrs:
1314         while (--i >= 0)
1315                 __arm_smmu_free_bitmap(smmu->smr_map, smrs[i].idx);
1316         kfree(smrs);
1317         return -ENOSPC;
1318 }
1319
1320 static void arm_smmu_master_free_smrs(struct arm_smmu_device *smmu,
1321                                       struct arm_smmu_master_cfg *cfg)
1322 {
1323         int i;
1324         void __iomem *gr0_base = ARM_SMMU_GR0(smmu);
1325         struct arm_smmu_smr *smrs = cfg->smrs;
1326
1327         if (!smrs)
1328                 return;
1329
1330         /* Invalidate the SMRs before freeing back to the allocator */
1331         for (i = 0; i < cfg->num_streamids; ++i) {
1332                 u8 idx = smrs[i].idx;
1333
1334                 writel_relaxed(~SMR_VALID, gr0_base + ARM_SMMU_GR0_SMR(idx));
1335                 __arm_smmu_free_bitmap(smmu->smr_map, idx);
1336         }
1337
1338         cfg->smrs = NULL;
1339         kfree(smrs);
1340 }
1341
1342 #ifdef CONFIG_ARM_SMMU_WAR
1343 /* HACK: c-model uses legacy swgroup interface */
1344 static void tegra_smmu_conf_swgroup(struct arm_smmu_device *smmu, int swgid,
1345                                     u8 cbndx)
1346 {
1347         size_t offs;
1348         u32 val;
1349
1350         offs = tegra_smmu_of_offset(swgid);
1351         val = BIT(31) | swgid; /* swgid == streamID */
1352         __writel(val, mc_base + offs);
1353
1354         pr_info("%s() ASID_0=0x%zx val=0x%08x streamID=%d cbndx=%d\n",
1355                 __func__, offs, val, swgid, cbndx);
1356 }
1357 #else
1358 static inline void tegra_smmu_conf_swgroup(struct arm_smmu_device *smmu,
1359                                            int swgid, u8 cbndx)
1360 {
1361 }
1362 #endif
1363
1364 static int arm_smmu_domain_add_master(struct arm_smmu_domain *smmu_domain,
1365                                       struct arm_smmu_master_cfg *cfg)
1366 {
1367         int i, ret;
1368         struct arm_smmu_device *smmu = smmu_domain->smmu;
1369         void __iomem *gr0_base = ARM_SMMU_GR0(smmu);
1370
1371         /* Devices in an IOMMU group may already be configured */
1372         ret = arm_smmu_master_configure_smrs(smmu, cfg);
1373         if (ret)
1374                 return ret == -EEXIST ? 0 : ret;
1375
1376         for (i = 0; i < cfg->num_streamids; ++i) {
1377                 u32 idx, s2cr;
1378
1379                 idx = cfg->smrs ? cfg->smrs[i].idx : cfg->streamids[i];
1380                 s2cr = S2CR_TYPE_TRANS |
1381                        (smmu_domain->cfg.cbndx << S2CR_CBNDX_SHIFT);
1382                 writel_relaxed(s2cr, gr0_base + ARM_SMMU_GR0_S2CR(idx));
1383
1384                 if (config_enabled(CONFIG_ARM_SMMU_WAR) &&
1385                     tegra_platform_is_linsim())
1386                         tegra_smmu_conf_swgroup(smmu, cfg->streamids[i],
1387                                                 smmu_domain->cfg.cbndx);
1388         }
1389
1390         return 0;
1391 }
1392
1393 static void arm_smmu_domain_remove_master(struct arm_smmu_domain *smmu_domain,
1394                                           struct arm_smmu_master_cfg *cfg)
1395 {
1396         int i;
1397         struct arm_smmu_device *smmu = smmu_domain->smmu;
1398         void __iomem *gr0_base = ARM_SMMU_GR0(smmu);
1399
1400         /* An IOMMU group is torn down by the first device to be removed */
1401         if ((smmu->features & ARM_SMMU_FEAT_STREAM_MATCH) && !cfg->smrs)
1402                 return;
1403
1404         /*
1405          * We *must* clear the S2CR first, because freeing the SMR means
1406          * that it can be re-allocated immediately.
1407          */
1408         for (i = 0; i < cfg->num_streamids; ++i) {
1409                 u32 idx = cfg->smrs ? cfg->smrs[i].idx : cfg->streamids[i];
1410
1411                 writel_relaxed(S2CR_TYPE_BYPASS,
1412                                gr0_base + ARM_SMMU_GR0_S2CR(idx));
1413         }
1414
1415         arm_smmu_master_free_smrs(smmu, cfg);
1416 }
1417
1418 static int smmu_ptdump_show(struct seq_file *s, void *unused)
1419 {
1420         struct arm_smmu_domain *smmu_domain = s->private;
1421         struct arm_smmu_cfg *cfg = &smmu_domain->cfg;
1422         pgd_t *pgd;
1423         pud_t *pud;
1424         pmd_t *pmd;
1425         pte_t *pte;
1426         int i, j, k, l;
1427         unsigned long addr = 0;
1428
1429         pgd = cfg->pgd;
1430         for (i = 0; i < PTRS_PER_PGD;
1431                 ++i, pgd++, addr += PGDIR_SIZE) {
1432                 if (pgd_none(*pgd))
1433                         continue;
1434                 pud = pud_offset(pgd, addr);
1435                 for (j = 0; j < PTRS_PER_PUD; ++j, pud++) {
1436                         if (pud_none(*pud)) {
1437                                 if ((ulong)pgd != (ulong)pud)
1438                                         addr += PUD_SIZE;
1439                                 continue;
1440                         }
1441                         pmd = pmd_offset(pud, addr);
1442                         for (k = 0; k < PTRS_PER_PMD;
1443                                 ++k, pmd++, addr += PMD_SIZE) {
1444                                 if (pmd_none(*pmd))
1445                                         continue;
1446                                 pte = pmd_page_vaddr(*pmd) + pte_index(addr);
1447                                 for (l = 0; l < PTRS_PER_PTE;
1448                                         ++l, pte++, addr += PAGE_SIZE) {
1449                                         phys_addr_t pa;
1450
1451                                         pa = __pfn_to_phys(pte_pfn(*pte));
1452                                         if (!pa)
1453                                                 continue;
1454                                         seq_printf(s,
1455                                                    "va=0x%016lx pa=%pap *pte=%pad\n",
1456                                                    addr, &pa, &(*pte));
1457                                 }
1458                         }
1459                         if ((ulong)pgd != (ulong)pud)
1460                                 addr += PUD_SIZE;
1461                 }
1462         }
1463         return 0;
1464 }
1465
1466 static int smmu_ptdump_open(struct inode *inode, struct file *file)
1467 {
1468         return single_open(file, smmu_ptdump_show, inode->i_private);
1469 }
1470
1471 static const struct file_operations smmu_ptdump_fops = {
1472         .open           = smmu_ptdump_open,
1473         .read           = seq_read,
1474         .llseek         = seq_lseek,
1475         .release        = single_release,
1476 };
1477
1478 #define defreg_cb(_name)                        \
1479         {                                       \
1480                 .name = __stringify(_name),     \
1481                 .offset = ARM_SMMU_CB_ ## _name,\
1482         }
1483
1484 static const struct debugfs_reg32 arm_smmu_cb_regs[] = {
1485         defreg_cb(SCTLR),
1486         defreg_cb(TTBCR2),
1487         defreg_cb(TTBR0_LO),
1488         defreg_cb(TTBR0_HI),
1489         defreg_cb(TTBCR),
1490         defreg_cb(S1_MAIR0),
1491         defreg_cb(FSR),
1492         defreg_cb(FAR_LO),
1493         defreg_cb(FAR_HI),
1494         defreg_cb(FSYNR0),
1495 };
1496
1497 static ssize_t smmu_debugfs_iova2phys_write(struct file *file,
1498                                             const char __user *buffer,
1499                                             size_t count, loff_t *pos)
1500 {
1501         int ret;
1502         struct iommu_domain *domain = file_inode(file)->i_private;
1503         struct arm_smmu_domain *smmu_domain = domain->priv;
1504         char str[] = "0x0123456789abcdef";
1505         unsigned long flags;
1506         dma_addr_t tmp;
1507
1508         count = min_t(size_t, strlen(str), count);
1509         if (copy_from_user(str, buffer, count))
1510                 return -EINVAL;
1511
1512         ret = sscanf(str, "0x%llx", &tmp);
1513         if (ret != 1)
1514                 return -EINVAL;
1515
1516         spin_lock_irqsave(&smmu_domain->lock, flags);
1517         smmu_domain->inquired_iova = tmp;
1518         smmu_domain->inquired_phys =
1519                 arm_smmu_iova_to_phys(domain, smmu_domain->inquired_iova);
1520         pr_info("iova=%pa pa=%pa\n",
1521                 &smmu_domain->inquired_iova, &smmu_domain->inquired_phys);
1522         spin_unlock_irqrestore(&smmu_domain->lock, flags);
1523         return count;
1524 }
1525
1526 static int smmu_iova2phys_show(struct seq_file *m, void *v)
1527 {
1528         struct iommu_domain *domain = m->private;
1529         struct arm_smmu_domain *smmu_domain = domain->priv;
1530         unsigned long flags;
1531
1532         spin_lock_irqsave(&smmu_domain->lock, flags);
1533
1534         seq_printf(m, "iova=%pa pa=%pa\n",
1535                    &smmu_domain->inquired_iova,
1536                    &smmu_domain->inquired_phys);
1537
1538         spin_unlock_irqrestore(&smmu_domain->lock, flags);
1539         return 0;
1540 }
1541
1542 static int smmu_iova2phys_open(struct inode *inode, struct file *file)
1543 {
1544         return single_open(file, smmu_iova2phys_show, inode->i_private);
1545 }
1546
1547 static const struct file_operations smmu_iova2phys_fops = {
1548         .open           = smmu_iova2phys_open,
1549         .read           = seq_read,
1550         .llseek         = seq_lseek,
1551         .release        = single_release,
1552         .write          = smmu_debugfs_iova2phys_write,
1553 };
1554
1555 static void debugfs_create_smmu_cb(struct iommu_domain *domain,
1556                                    struct device *dev)
1557 {
1558         struct dentry *dent;
1559         char name[] = "cb000";
1560         struct debugfs_regset32 *cb;
1561         struct arm_smmu_domain *smmu_domain = domain->priv;
1562         u8 cbndx = smmu_domain->cfg.cbndx;
1563         struct arm_smmu_device *smmu = smmu_domain->smmu;
1564
1565         sprintf(name, "cb%03d", cbndx);
1566         dent = debugfs_create_dir(name, smmu->debugfs_root);
1567         if (!dent)
1568                 return;
1569         cb = smmu->regset + 1 + cbndx;
1570         cb->regs = arm_smmu_cb_regs;
1571         cb->nregs = ARRAY_SIZE(arm_smmu_cb_regs);
1572         cb->base = smmu->base + (smmu->size >> 1) +
1573                 cbndx * (1 << smmu->pgshift);
1574         debugfs_create_regset32("regdump", S_IRUGO, dent, cb);
1575         debugfs_create_file("ptdump", S_IRUGO, dent, smmu_domain,
1576                             &smmu_ptdump_fops);
1577         debugfs_create_file("iova_to_phys", S_IRUSR, dent, domain,
1578                             &smmu_iova2phys_fops);
1579 }
1580
1581 static int smmu_master_show(struct seq_file *s, void *unused)
1582 {
1583         int i;
1584         struct arm_smmu_master *master = s->private;
1585
1586         for (i = 0; i < master->cfg.num_streamids; i++)
1587                 seq_printf(s, "streamids: % 3d ", master->cfg.streamids[i]);
1588         seq_printf(s, "\n");
1589         for (i = 0; i < master->cfg.num_streamids; i++)
1590                 seq_printf(s, "smrs:      % 3d ", master->cfg.smrs[i].idx);
1591         seq_printf(s, "\n");
1592         return 0;
1593 }
1594
1595 static int smmu_master_open(struct inode *inode, struct file *file)
1596 {
1597         return single_open(file, smmu_master_show, inode->i_private);
1598 }
1599
1600 static const struct file_operations smmu_master_fops = {
1601         .open           = smmu_master_open,
1602         .read           = seq_read,
1603         .llseek         = seq_lseek,
1604         .release        = single_release,
1605 };
1606
1607 static void add_smmu_master_debugfs(struct iommu_domain *domain,
1608                                     struct device *dev,
1609                                     struct arm_smmu_master *master)
1610 {
1611         struct dentry *dent;
1612         struct arm_smmu_domain *smmu_domain = domain->priv;
1613         struct arm_smmu_device *smmu = smmu_domain->smmu;
1614         char name[] = "cb000";
1615         char target[] = "../../cb000";
1616         u8 cbndx = smmu_domain->cfg.cbndx;
1617
1618         dent = debugfs_create_dir(dev_name(dev), smmu->masters_root);
1619         if (!dent)
1620                 return;
1621
1622         debugfs_create_file("streamids", 0444, dent, master, &smmu_master_fops);
1623         debugfs_create_u8("cbndx", 0444, dent, &smmu_domain->cfg.cbndx);
1624         debugfs_create_smmu_cb(domain, dev);
1625         sprintf(name, "cb%03d", cbndx);
1626         sprintf(target, "../../cb%03d", cbndx);
1627         debugfs_create_symlink(name, dent, target);
1628         master->debugfs_root = dent;
1629 }
1630
1631 static int arm_smmu_attach_dev(struct iommu_domain *domain, struct device *dev)
1632 {
1633         int ret;
1634         struct arm_smmu_domain *smmu_domain = domain->priv;
1635         struct arm_smmu_device *smmu, *dom_smmu;
1636         struct arm_smmu_master_cfg *cfg;
1637
1638         smmu = find_smmu_for_device(dev);
1639         if (!smmu) {
1640                 dev_err(dev, "cannot attach to SMMU, is it on the same bus?\n");
1641                 return -ENXIO;
1642         }
1643
1644         if (dev->archdata.iommu) {
1645                 dev_err(dev, "already attached to IOMMU domain\n");
1646                 return -EEXIST;
1647         }
1648
1649         /*
1650          * Sanity check the domain. We don't support domains across
1651          * different SMMUs.
1652          */
1653         dom_smmu = ACCESS_ONCE(smmu_domain->smmu);
1654         if (!dom_smmu) {
1655                 /* Now that we have a master, we can finalise the domain */
1656                 ret = arm_smmu_init_domain_context(domain, smmu);
1657                 if (IS_ERR_VALUE(ret))
1658                         return ret;
1659
1660                 dom_smmu = smmu_domain->smmu;
1661         }
1662
1663         if (dom_smmu != smmu) {
1664                 dev_err(dev,
1665                         "cannot attach to SMMU %s whilst already attached to domain on SMMU %s\n",
1666                         dev_name(smmu_domain->smmu->dev), dev_name(smmu->dev));
1667                 return -EINVAL;
1668         }
1669
1670         /* Looks ok, so add the device to the domain */
1671         cfg = find_smmu_master_cfg(dev);
1672         if (!cfg)
1673                 return -ENODEV;
1674
1675         ret = arm_smmu_domain_add_master(smmu_domain, cfg);
1676         if (!ret) {
1677                 dev->archdata.iommu = domain;
1678                 add_smmu_master_debugfs(domain, dev,
1679                                         find_smmu_master(smmu, dev->of_node));
1680         }
1681         return ret;
1682 }
1683
1684 static void arm_smmu_detach_dev(struct iommu_domain *domain, struct device *dev)
1685 {
1686         struct arm_smmu_domain *smmu_domain = domain->priv;
1687         struct arm_smmu_master_cfg *cfg;
1688
1689         cfg = find_smmu_master_cfg(dev);
1690         if (!cfg)
1691                 return;
1692
1693         debugfs_remove_recursive(cfg->debugfs_root);
1694         dev->archdata.iommu = NULL;
1695         arm_smmu_domain_remove_master(smmu_domain, cfg);
1696 }
1697
1698 static bool arm_smmu_pte_is_contiguous_range(unsigned long addr,
1699                                         unsigned long end, unsigned long phys)
1700 {
1701         return !(addr & ~ARM_SMMU_PTE_CONT_MASK) &&
1702                 (addr + ARM_SMMU_PTE_CONT_SIZE <= end) &&
1703                 !(phys & ~ARM_SMMU_PTE_CONT_MASK);
1704 }
1705
1706 static int arm_smmu_alloc_init_pte(struct arm_smmu_device *smmu, pmd_t *pmd,
1707                                    unsigned long addr, unsigned long end,
1708                                    unsigned long pfn, int prot, int stage)
1709 {
1710         pte_t *pte, *start;
1711         pteval_t pteval = ARM_SMMU_PTE_PAGE | ARM_SMMU_PTE_AF | ARM_SMMU_PTE_XN;
1712
1713         if (pmd_none(*pmd)) {
1714                 /* Allocate a new set of tables */
1715                 pgtable_t table = alloc_page(GFP_ATOMIC|__GFP_ZERO);
1716
1717                 if (!table)
1718                         return -ENOMEM;
1719
1720                 arm_smmu_flush_pgtable(smmu, page_address(table), PAGE_SIZE);
1721                 pmd_populate(NULL, pmd, table);
1722                 arm_smmu_flush_pgtable(smmu, pmd, sizeof(*pmd));
1723         }
1724
1725         if (stage == 1) {
1726                 pteval |= ARM_SMMU_PTE_AP_UNPRIV | ARM_SMMU_PTE_nG;
1727                 if (!(prot & IOMMU_WRITE) && (prot & IOMMU_READ))
1728                         pteval |= ARM_SMMU_PTE_AP_RDONLY;
1729
1730                 if (prot & IOMMU_CACHE)
1731                         pteval |= (MAIR_ATTR_IDX_CACHE <<
1732                                    ARM_SMMU_PTE_ATTRINDX_SHIFT);
1733         } else {
1734                 pteval |= ARM_SMMU_PTE_HAP_FAULT;
1735                 if (prot & IOMMU_READ)
1736                         pteval |= ARM_SMMU_PTE_HAP_READ;
1737                 if (prot & IOMMU_WRITE)
1738                         pteval |= ARM_SMMU_PTE_HAP_WRITE;
1739                 if (prot & IOMMU_CACHE)
1740                         pteval |= ARM_SMMU_PTE_MEMATTR_OIWB;
1741                 else
1742                         pteval |= ARM_SMMU_PTE_MEMATTR_NC;
1743         }
1744
1745         /* If no access, create a faulting entry to avoid TLB fills */
1746         if (prot & IOMMU_EXEC)
1747                 pteval &= ~ARM_SMMU_PTE_XN;
1748         else if (!(prot & (IOMMU_READ | IOMMU_WRITE)))
1749                 pteval &= ~ARM_SMMU_PTE_PAGE;
1750
1751         pteval |= ARM_SMMU_PTE_SH_IS;
1752         start = pmd_page_vaddr(*pmd) + pte_index(addr);
1753         pte = start;
1754
1755         /*
1756          * Install the page table entries. This is fairly complicated
1757          * since we attempt to make use of the contiguous hint in the
1758          * ptes where possible. The contiguous hint indicates a series
1759          * of ARM_SMMU_PTE_CONT_ENTRIES ptes mapping a physically
1760          * contiguous region with the following constraints:
1761          *
1762          *   - The region start is aligned to ARM_SMMU_PTE_CONT_SIZE
1763          *   - Each pte in the region has the contiguous hint bit set
1764          *
1765          * This complicates unmapping (also handled by this code, when
1766          * neither IOMMU_READ or IOMMU_WRITE are set) because it is
1767          * possible, yet highly unlikely, that a client may unmap only
1768          * part of a contiguous range. This requires clearing of the
1769          * contiguous hint bits in the range before installing the new
1770          * faulting entries.
1771          *
1772          * Note that re-mapping an address range without first unmapping
1773          * it is not supported, so TLB invalidation is not required here
1774          * and is instead performed at unmap and domain-init time.
1775          */
1776         do {
1777                 int i = 1;
1778
1779                 pteval &= ~ARM_SMMU_PTE_CONT;
1780
1781                 if (arm_smmu_pte_is_contiguous_range(addr, end, __pfn_to_phys(pfn))) {
1782                         i = ARM_SMMU_PTE_CONT_ENTRIES;
1783                         pteval |= ARM_SMMU_PTE_CONT;
1784                 } else if (pte_val(*pte) &
1785                            (ARM_SMMU_PTE_CONT | ARM_SMMU_PTE_PAGE)) {
1786                         int j;
1787                         pte_t *cont_start;
1788                         unsigned long idx = pte_index(addr);
1789
1790                         idx &= ~(ARM_SMMU_PTE_CONT_ENTRIES - 1);
1791                         cont_start = pmd_page_vaddr(*pmd) + idx;
1792                         for (j = 0; j < ARM_SMMU_PTE_CONT_ENTRIES; ++j)
1793                                 pte_val(*(cont_start + j)) &=
1794                                         ~ARM_SMMU_PTE_CONT;
1795
1796                         arm_smmu_flush_pgtable(smmu, cont_start,
1797                                                sizeof(*pte) *
1798                                                ARM_SMMU_PTE_CONT_ENTRIES);
1799                 }
1800
1801                 if (!pfn) {
1802                         memset(pte, 0, i * sizeof(*pte));
1803                         addr += i * PAGE_SIZE;
1804                         pte += i;
1805                         break;
1806                 }
1807
1808                 do {
1809                         *pte = pfn_pte(pfn, __pgprot(pteval));
1810                 } while (pte++, pfn++, addr += PAGE_SIZE, --i);
1811         } while (addr != end);
1812
1813         arm_smmu_flush_pgtable(smmu, start, sizeof(*pte) * (pte - start));
1814         return 0;
1815 }
1816
1817 static int arm_smmu_alloc_init_pmd(struct arm_smmu_device *smmu, pud_t *pud,
1818                                    unsigned long addr, unsigned long end,
1819                                    phys_addr_t phys, int prot, int stage)
1820 {
1821         int ret;
1822         pmd_t *pmd;
1823         unsigned long next, pfn = __phys_to_pfn(phys);
1824
1825 #ifndef __PAGETABLE_PMD_FOLDED
1826         if (pud_none(*pud)) {
1827                 pmd = (pmd_t *)get_zeroed_page(GFP_ATOMIC);
1828                 if (!pmd)
1829                         return -ENOMEM;
1830
1831                 arm_smmu_flush_pgtable(smmu, pmd, PAGE_SIZE);
1832                 pud_populate(NULL, pud, pmd);
1833                 arm_smmu_flush_pgtable(smmu, pud, sizeof(*pud));
1834
1835                 pmd += pmd_index(addr);
1836         } else
1837 #endif
1838                 pmd = pmd_offset(pud, addr);
1839
1840         do {
1841                 next = pmd_addr_end(addr, end);
1842                 ret = arm_smmu_alloc_init_pte(smmu, pmd, addr, next, pfn,
1843                                               prot, stage);
1844                 if (phys)
1845                         phys += next - addr;
1846                 pfn = __phys_to_pfn(phys);
1847         } while (pmd++, addr = next, addr < end);
1848
1849         return ret;
1850 }
1851
1852 static int arm_smmu_alloc_init_pud(struct arm_smmu_device *smmu, pgd_t *pgd,
1853                                    unsigned long addr, unsigned long end,
1854                                    phys_addr_t phys, int prot, int stage)
1855 {
1856         int ret = 0;
1857         pud_t *pud;
1858         unsigned long next;
1859
1860 #ifndef __PAGETABLE_PUD_FOLDED
1861         if (pgd_none(*pgd)) {
1862                 pud = (pud_t *)get_zeroed_page(GFP_ATOMIC);
1863                 if (!pud)
1864                         return -ENOMEM;
1865
1866                 arm_smmu_flush_pgtable(smmu, pud, PAGE_SIZE);
1867                 pgd_populate(NULL, pgd, pud);
1868                 arm_smmu_flush_pgtable(smmu, pgd, sizeof(*pgd));
1869
1870                 pud += pud_index(addr);
1871         } else
1872 #endif
1873                 pud = pud_offset(pgd, addr);
1874
1875         do {
1876                 next = pud_addr_end(addr, end);
1877                 ret = arm_smmu_alloc_init_pmd(smmu, pud, addr, next, phys,
1878                                               prot, stage);
1879                 if (phys)
1880                         phys += next - addr;
1881         } while (pud++, addr = next, addr < end);
1882
1883         return ret;
1884 }
1885
1886 #define FLUSH_TLB_AFTER_MAP 1
1887
1888 static int arm_smmu_handle_mapping(struct arm_smmu_domain *smmu_domain,
1889                                    unsigned long iova, phys_addr_t paddr,
1890                                    size_t size, unsigned long attrs)
1891 {
1892         int ret, stage, prot = IOMMU_WRITE | IOMMU_READ;
1893         unsigned long end;
1894         phys_addr_t input_mask, output_mask;
1895         struct arm_smmu_device *smmu = smmu_domain->smmu;
1896         struct arm_smmu_cfg *cfg = &smmu_domain->cfg;
1897         pgd_t *pgd = cfg->pgd;
1898         unsigned long flags;
1899
1900         /* FIXME: follow the upstream prot */
1901         if (dma_get_attr(DMA_ATTR_READ_ONLY, (struct dma_attrs *)attrs))
1902                 prot &= ~IOMMU_WRITE;
1903         else if (dma_get_attr(DMA_ATTR_WRITE_ONLY, (struct dma_attrs *)attrs))
1904                 prot &= ~IOMMU_READ;
1905
1906         if (cfg->cbar == CBAR_TYPE_S2_TRANS) {
1907                 stage = 2;
1908                 input_mask = (1ULL << smmu->s2_input_size) - 1;
1909                 output_mask = (1ULL << smmu->s2_output_size) - 1;
1910         } else {
1911                 stage = 1;
1912                 input_mask = (1ULL << smmu->s1_input_size) - 1;
1913                 output_mask = (1ULL << smmu->s1_output_size) - 1;
1914         }
1915
1916         if (!pgd)
1917                 return -EINVAL;
1918
1919         if (size & ~PAGE_MASK)
1920                 return -EINVAL;
1921
1922         if ((phys_addr_t)iova & ~input_mask)
1923                 return -ERANGE;
1924
1925         if (paddr & ~output_mask)
1926                 return -ERANGE;
1927
1928         if (test_bit(cfg->cbndx, smmu->context_filter)) {
1929                 trace_smmu_map(cfg->cbndx, iova, paddr, size, prot);
1930                 pr_debug("cbndx=%d iova=%pad paddr=%pap size=%zx prot=%x skip=%d\n",
1931                          cfg->cbndx, &iova, &paddr, size, prot,
1932                          arm_smmu_skip_mapping);
1933         }
1934
1935         if (arm_smmu_skip_mapping)
1936                 return 0;
1937
1938         spin_lock_irqsave(&smmu_domain->lock, flags);
1939         pgd += pgd_index(iova);
1940         end = iova + size;
1941         do {
1942                 unsigned long next = pgd_addr_end(iova, end);
1943
1944                 ret = arm_smmu_alloc_init_pud(smmu, pgd, iova, next, paddr,
1945                                               prot, stage);
1946                 if (ret)
1947                         goto out_unlock;
1948
1949                 if (paddr)
1950                         paddr += next - iova;
1951                 iova = next;
1952         } while (pgd++, iova != end);
1953
1954 out_unlock:
1955         spin_unlock_irqrestore(&smmu_domain->lock, flags);
1956         if (FLUSH_TLB_AFTER_MAP)
1957                 arm_smmu_tlb_inv_context(smmu_domain);
1958
1959         return ret;
1960 }
1961
1962 static int arm_smmu_map_sg(struct iommu_domain *domain, unsigned long iova,
1963                         struct scatterlist *sgl, int npages, unsigned long prot)
1964 {
1965         int i;
1966         struct scatterlist *sg;
1967         struct arm_smmu_domain *smmu_domain = domain->priv;
1968
1969         for (i = 0, sg = sgl; i < npages; sg = sg_next(sg)) {
1970                 int err;
1971                 phys_addr_t pa = sg_phys(sg) & PAGE_MASK;
1972                 unsigned int len = PAGE_ALIGN(sg->offset + sg->length);
1973
1974                 pr_debug("%s() iova=%pad pa=%pap size=%x\n",
1975                         __func__, &iova, &pa, len);
1976                 err = arm_smmu_handle_mapping(smmu_domain, iova, pa, len, prot);
1977                 if (err)
1978                         return err;
1979
1980                 i += len >> PAGE_SHIFT;
1981                 iova += len;
1982         }
1983
1984         return 0;
1985 }
1986
1987 static int arm_smmu_map(struct iommu_domain *domain, unsigned long iova,
1988                         phys_addr_t paddr, size_t size, unsigned long prot)
1989 {
1990         struct arm_smmu_domain *smmu_domain = domain->priv;
1991
1992         if (!smmu_domain)
1993                 return -ENODEV;
1994
1995         return arm_smmu_handle_mapping(smmu_domain, iova, paddr, size, prot);
1996 }
1997
1998 static size_t arm_smmu_unmap(struct iommu_domain *domain, unsigned long iova,
1999                              size_t size)
2000 {
2001         int ret;
2002         struct arm_smmu_domain *smmu_domain = domain->priv;
2003
2004         ret = arm_smmu_handle_mapping(smmu_domain, iova, 0, size, 0);
2005         if (!FLUSH_TLB_AFTER_MAP)
2006                 arm_smmu_tlb_inv_context(smmu_domain);
2007         return ret ? 0 : size;
2008 }
2009
2010 static phys_addr_t arm_smmu_iova_to_phys(struct iommu_domain *domain,
2011                                          dma_addr_t iova)
2012 {
2013         pgd_t *pgdp, pgd;
2014         pud_t pud;
2015         pmd_t pmd;
2016         pte_t pte;
2017         struct arm_smmu_domain *smmu_domain = domain->priv;
2018         struct arm_smmu_cfg *cfg = &smmu_domain->cfg;
2019
2020         pgdp = cfg->pgd;
2021         if (!pgdp)
2022                 return 0;
2023
2024         pgd = *(pgdp + pgd_index(iova));
2025         if (pgd_none(pgd))
2026                 return 0;
2027
2028         pud = *pud_offset(&pgd, iova);
2029         if (pud_none(pud))
2030                 return 0;
2031
2032         pmd = *pmd_offset(&pud, iova);
2033         if (pmd_none(pmd))
2034                 return 0;
2035
2036         pte = *(pmd_page_vaddr(pmd) + pte_index(iova));
2037         if (pte_none(pte))
2038                 return 0;
2039
2040         return __pfn_to_phys(pte_pfn(pte)) | (iova & ~PAGE_MASK);
2041 }
2042
2043 static bool arm_smmu_capable(enum iommu_cap cap)
2044 {
2045         switch (cap) {
2046         case IOMMU_CAP_CACHE_COHERENCY:
2047                 /*
2048                  * Return true here as the SMMU can always send out coherent
2049                  * requests.
2050                  */
2051                 return true;
2052         case IOMMU_CAP_INTR_REMAP:
2053                 return true; /* MSIs are just memory writes */
2054         default:
2055                 return false;
2056         }
2057 }
2058
2059 static int __arm_smmu_get_pci_sid(struct pci_dev *pdev, u16 alias, void *data)
2060 {
2061         *((u16 *)data) = alias;
2062         return 0; /* Continue walking */
2063 }
2064
2065 static void __arm_smmu_release_pci_iommudata(void *data)
2066 {
2067         kfree(data);
2068 }
2069
2070 static int arm_iommu_fault(struct iommu_domain *domain, struct device *dev,
2071                 unsigned long iova, int flags, void *token)
2072 {
2073         struct arm_smmu_domain *smmu_domain = domain->priv;
2074         phys_addr_t dummy = page_to_phys(smmu_domain->arm_dummy_page);
2075         phys_addr_t pa = arm_smmu_iova_to_phys(domain, iova);
2076
2077         dev_err(dev, "%s: iova=0x%lx pa=%pa flags=0x%x cb=%d\n",
2078                 __func__, iova, &pa, flags, smmu_domain->cfg.cbndx);
2079
2080         if (arm_smmu_skip_mapping)
2081                 arm_smmu_skip_mapping = 0;
2082
2083         dev_err(dev, "%s: iova=0x%lx dummy=%pa flags=0x%x cb=%d\n",
2084                 __func__, iova, &dummy, flags, smmu_domain->cfg.cbndx);
2085
2086         arm_smmu_handle_mapping(smmu_domain, iova, dummy, PAGE_SIZE, 0);
2087         if (!FLUSH_TLB_AFTER_MAP)
2088                 arm_smmu_tlb_inv_context(smmu_domain);
2089
2090         return 0;
2091 }
2092
2093 static int arm_smmu_add_device(struct device *dev)
2094 {
2095         struct arm_smmu_device *smmu;
2096         struct arm_smmu_master_cfg *cfg;
2097         struct iommu_group *group;
2098         void (*releasefn)(void *) = NULL;
2099         int ret;
2100         struct dma_iommu_mapping *mapping;
2101         u64 swgids = 0;
2102
2103         smmu = find_smmu_for_device(dev);
2104         if (!smmu)
2105                 return -ENODEV;
2106
2107         group = iommu_group_alloc();
2108         if (IS_ERR(group)) {
2109                 dev_err(dev, "Failed to allocate IOMMU group\n");
2110                 return PTR_ERR(group);
2111         }
2112
2113         if (dev_is_pci(dev)) {
2114                 struct pci_dev *pdev = to_pci_dev(dev);
2115
2116                 cfg = kzalloc(sizeof(*cfg), GFP_KERNEL);
2117                 if (!cfg) {
2118                         ret = -ENOMEM;
2119                         goto out_put_group;
2120                 }
2121
2122                 cfg->num_streamids = 1;
2123                 swgids = TEGRA_SWGROUP_BIT(AFI);
2124                 /*
2125                  * Assume Stream ID == Requester ID for now.
2126                  * We need a way to describe the ID mappings in FDT.
2127                  */
2128                 pci_for_each_dma_alias(pdev, __arm_smmu_get_pci_sid,
2129                                        &cfg->streamids[0]);
2130                 releasefn = __arm_smmu_release_pci_iommudata;
2131         } else {
2132                 int i, sid;
2133                 struct arm_smmu_master *master;
2134
2135                 master = find_smmu_master(smmu, dev->of_node);
2136                 if (!master) {
2137                         ret = -ENODEV;
2138                         goto out_put_group;
2139                 }
2140
2141                 sid = master->cfg.streamids[0];
2142                 BUG_ON(sid < 0);
2143                 BUG_ON(sid >= NUM_SID);
2144                 cfg = arm_smmu_master_cfgs[sid];
2145                 BUG_ON(!cfg);
2146                 master->cfg.smrs = cfg->smrs;
2147
2148                 for (i = 0; i < cfg->num_streamids; i++)
2149                         swgids |= BIT(cfg->streamids[i]);
2150
2151                 dev_info(dev, "swgids=%llx\n", swgids);
2152         }
2153
2154         iommu_group_set_iommudata(group, cfg, releasefn);
2155         ret = iommu_group_add_device(group, dev);
2156 out_put_group:
2157         iommu_group_put(group);
2158         if (ret)
2159                 return ret;
2160
2161
2162         mapping = tegra_smmu_of_get_mapping(dev, swgids, &smmu->asprops);
2163         if (IS_ERR(mapping)) {
2164                 ret = PTR_ERR(mapping);
2165                 goto err_create_mapping;
2166         }
2167
2168         ret = arm_iommu_attach_device(dev, mapping);
2169         if (ret)
2170                 goto err_attach_dev;
2171
2172         if (smmu->options & ARM_SMMU_OPT_BROKEN_SIM_IRQ)
2173                 iommu_set_fault_handler(mapping->domain, arm_iommu_fault, 0);
2174
2175         return 0;
2176
2177 err_attach_dev:
2178         dev->archdata.iommu = NULL;
2179         arm_iommu_release_mapping(mapping);
2180 err_create_mapping:
2181         iommu_group_put(group);
2182         return ret;
2183 }
2184
2185 static void arm_smmu_remove_device(struct device *dev)
2186 {
2187         iommu_group_remove_device(dev);
2188 }
2189
2190 static struct iommu_ops arm_smmu_ops = {
2191         .capable        = arm_smmu_capable,
2192         .domain_init    = arm_smmu_domain_init,
2193         .domain_destroy = arm_smmu_domain_destroy,
2194         .attach_dev     = arm_smmu_attach_dev,
2195         .detach_dev     = arm_smmu_detach_dev,
2196         .get_hwid       = arm_smmu_get_hwid,
2197         .map_sg         = arm_smmu_map_sg,
2198         .map            = arm_smmu_map,
2199         .unmap          = arm_smmu_unmap,
2200         .iova_to_phys   = arm_smmu_iova_to_phys,
2201         .add_device     = arm_smmu_add_device,
2202         .remove_device  = arm_smmu_remove_device,
2203         .pgsize_bitmap  = (SECTION_SIZE |
2204                            ARM_SMMU_PTE_CONT_SIZE |
2205                            PAGE_SIZE),
2206 };
2207
2208 static void arm_smmu_device_reset(struct arm_smmu_device *smmu)
2209 {
2210         void __iomem *gr0_base = ARM_SMMU_GR0(smmu);
2211         void __iomem *cb_base;
2212         int i = 0;
2213         u32 reg;
2214
2215         /* clear global FSR */
2216         reg = readl_relaxed(ARM_SMMU_GR0_NS(smmu) + ARM_SMMU_GR0_sGFSR);
2217         writel(reg, ARM_SMMU_GR0_NS(smmu) + ARM_SMMU_GR0_sGFSR);
2218
2219         /* Mark all SMRn as invalid and all S2CRn as bypass */
2220         for (i = 0; i < smmu->num_mapping_groups; ++i) {
2221                 writel_relaxed(0, gr0_base + ARM_SMMU_GR0_SMR(i));
2222                 writel_relaxed(S2CR_TYPE_BYPASS,
2223                         gr0_base + ARM_SMMU_GR0_S2CR(i));
2224         }
2225
2226         /* Make sure all context banks are disabled and clear CB_FSR  */
2227         for (i = 0; i < smmu->num_context_banks; ++i) {
2228                 cb_base = ARM_SMMU_CB_BASE(smmu) + ARM_SMMU_CB(smmu, i);
2229                 writel_relaxed(0, cb_base + ARM_SMMU_CB_SCTLR);
2230                 writel_relaxed(FSR_FAULT, cb_base + ARM_SMMU_CB_FSR);
2231         }
2232
2233         /* Invalidate the TLB, just in case */
2234         writel_relaxed(0, gr0_base + ARM_SMMU_GR0_STLBIALL);
2235         writel_relaxed(0, gr0_base + ARM_SMMU_GR0_TLBIALLH);
2236         writel_relaxed(0, gr0_base + ARM_SMMU_GR0_TLBIALLNSNH);
2237
2238         reg = readl_relaxed(ARM_SMMU_GR0_NS(smmu) + ARM_SMMU_GR0_sCR0);
2239
2240         /* Enable fault reporting */
2241         reg |= (sCR0_GFRE | sCR0_GFIE | sCR0_GCFGFRE | sCR0_GCFGFIE | sCR0_USFCFG);
2242
2243         /* Disable TLB broadcasting. */
2244         reg |= (sCR0_VMIDPNE | sCR0_PTM);
2245
2246         /* Enable client access, but bypass when no mapping is found */
2247         reg &= ~(sCR0_CLIENTPD);
2248
2249         /* Disable forced broadcasting */
2250         reg &= ~sCR0_FB;
2251
2252         /* Don't upgrade barriers */
2253         reg &= ~(sCR0_BSU_MASK << sCR0_BSU_SHIFT);
2254
2255         /* Push the button */
2256         arm_smmu_tlb_sync(smmu);
2257         writel(reg, ARM_SMMU_GR0_NS(smmu) + ARM_SMMU_GR0_sCR0);
2258 }
2259
2260 static int arm_smmu_id_size_to_bits(int size)
2261 {
2262         switch (size) {
2263         case 0:
2264                 return 32;
2265         case 1:
2266                 return 36;
2267         case 2:
2268                 return 40;
2269         case 3:
2270                 return 42;
2271         case 4:
2272                 return 44;
2273         case 5:
2274         default:
2275                 return 48;
2276         }
2277 }
2278
2279 static int arm_smmu_device_cfg_probe(struct arm_smmu_device *smmu)
2280 {
2281         unsigned long size;
2282         void __iomem *gr0_base = ARM_SMMU_GR0(smmu);
2283         u32 id;
2284
2285         dev_notice(smmu->dev, "probing hardware configuration...\n");
2286         dev_notice(smmu->dev, "SMMUv%d with:\n", smmu->version);
2287
2288         /* ID0 */
2289         id = readl_relaxed(gr0_base + ARM_SMMU_GR0_ID0);
2290 #ifndef CONFIG_64BIT
2291         if (((id >> ID0_PTFS_SHIFT) & ID0_PTFS_MASK) == ID0_PTFS_V8_ONLY) {
2292                 dev_err(smmu->dev, "\tno v7 descriptor support!\n");
2293                 return -ENODEV;
2294         }
2295 #endif
2296
2297         /* Restrict available stages based on module parameter */
2298         if (force_stage == 1)
2299                 id &= ~(ID0_S2TS | ID0_NTS);
2300         else if (force_stage == 2)
2301                 id &= ~(ID0_S1TS | ID0_NTS);
2302
2303         if (id & ID0_S1TS) {
2304                 smmu->features |= ARM_SMMU_FEAT_TRANS_S1;
2305                 dev_notice(smmu->dev, "\tstage 1 translation\n");
2306         }
2307
2308         if (id & ID0_S2TS) {
2309                 smmu->features |= ARM_SMMU_FEAT_TRANS_S2;
2310                 dev_notice(smmu->dev, "\tstage 2 translation\n");
2311         }
2312
2313         if (id & ID0_NTS) {
2314                 smmu->features |= ARM_SMMU_FEAT_TRANS_NESTED;
2315                 dev_notice(smmu->dev, "\tnested translation\n");
2316         }
2317
2318         if (!(smmu->features &
2319                 (ARM_SMMU_FEAT_TRANS_S1 | ARM_SMMU_FEAT_TRANS_S2))) {
2320                 dev_err(smmu->dev, "\tno translation support!\n");
2321                 return -ENODEV;
2322         }
2323
2324         if (id & ID0_CTTW) {
2325                 smmu->features |= ARM_SMMU_FEAT_COHERENT_WALK;
2326                 dev_notice(smmu->dev, "\tcoherent table walk\n");
2327         }
2328
2329         if (id & ID0_SMS) {
2330                 u32 smr, sid, mask;
2331
2332                 smmu->features |= ARM_SMMU_FEAT_STREAM_MATCH;
2333                 smmu->num_mapping_groups = (id >> ID0_NUMSMRG_SHIFT) &
2334                                            ID0_NUMSMRG_MASK;
2335                 if (smmu->num_mapping_groups == 0) {
2336                         dev_err(smmu->dev,
2337                                 "stream-matching supported, but no SMRs present!\n");
2338                         return -ENODEV;
2339                 }
2340
2341                 smr = SMR_MASK_MASK << SMR_MASK_SHIFT;
2342                 smr |= (SMR_ID_MASK << SMR_ID_SHIFT);
2343                 writel_relaxed(smr, gr0_base + ARM_SMMU_GR0_SMR(0));
2344                 smr = readl_relaxed(gr0_base + ARM_SMMU_GR0_SMR(0));
2345
2346                 mask = (smr >> SMR_MASK_SHIFT) & SMR_MASK_MASK;
2347                 sid = (smr >> SMR_ID_SHIFT) & SMR_ID_MASK;
2348                 if ((mask & sid) != sid) {
2349                         dev_err(smmu->dev,
2350                                 "SMR mask bits (0x%x) insufficient for ID field (0x%x)\n",
2351                                 mask, sid);
2352                         return -ENODEV;
2353                 }
2354
2355                 dev_notice(smmu->dev,
2356                            "\tstream matching with %u register groups, mask 0x%x",
2357                            smmu->num_mapping_groups, mask);
2358         } else {
2359                 smmu->num_mapping_groups = (id >> ID0_NUMSIDB_SHIFT) &
2360                                            ID0_NUMSIDB_MASK;
2361         }
2362
2363         /* ID1 */
2364         id = readl_relaxed(gr0_base + ARM_SMMU_GR0_ID1);
2365         smmu->pgshift = (id & ID1_PAGESIZE) ? 16 : 12;
2366
2367         /* Check for size mismatch of SMMU address space from mapped region */
2368         size = 1 <<
2369                 (((id >> ID1_NUMPAGENDXB_SHIFT) & ID1_NUMPAGENDXB_MASK) + 1);
2370         size *= 2 << smmu->pgshift;
2371         if (smmu->size != size) {
2372                 dev_info(smmu->dev,
2373                         "SMMU address space size (0x%lx) differs from mapped region size (0x%lx)!\n",
2374                         size, smmu->size);
2375                 smmu->size = size;
2376         }
2377
2378         smmu->num_s2_context_banks = (id >> ID1_NUMS2CB_SHIFT) &
2379                                       ID1_NUMS2CB_MASK;
2380         smmu->num_context_banks = (id >> ID1_NUMCB_SHIFT) & ID1_NUMCB_MASK;
2381         if (smmu->num_s2_context_banks > smmu->num_context_banks) {
2382                 dev_err(smmu->dev, "impossible number of S2 context banks!\n");
2383                 return -ENODEV;
2384         }
2385         dev_notice(smmu->dev, "\t%u context banks (%u stage-2 only)\n",
2386                    smmu->num_context_banks, smmu->num_s2_context_banks);
2387
2388         /* ID2 */
2389         id = readl_relaxed(gr0_base + ARM_SMMU_GR0_ID2);
2390         size = arm_smmu_id_size_to_bits((id >> ID2_IAS_SHIFT) & ID2_IAS_MASK);
2391         smmu->s1_output_size = min_t(unsigned long, PHYS_MASK_SHIFT, size);
2392
2393         /* Stage-2 input size limited due to pgd allocation (PTRS_PER_PGD) */
2394 #ifdef CONFIG_64BIT
2395         smmu->s2_input_size = min_t(unsigned long, VA_BITS, size);
2396 #else
2397         smmu->s2_input_size = min(32UL, size);
2398 #endif
2399
2400         /* The stage-2 output mask is also applied for bypass */
2401         size = arm_smmu_id_size_to_bits((id >> ID2_OAS_SHIFT) & ID2_OAS_MASK);
2402         smmu->s2_output_size = min_t(unsigned long, PHYS_MASK_SHIFT, size);
2403
2404         if (smmu->version == ARM_SMMU_V1) {
2405                 smmu->s1_input_size = 32;
2406         } else {
2407 #ifdef CONFIG_64BIT
2408                 size = (id >> ID2_UBS_SHIFT) & ID2_UBS_MASK;
2409                 size = min(VA_BITS, arm_smmu_id_size_to_bits(size));
2410 #else
2411                 size = 32;
2412 #endif
2413                 smmu->s1_input_size = size;
2414
2415                 if ((PAGE_SIZE == SZ_4K && !(id & ID2_PTFS_4K)) ||
2416                     (PAGE_SIZE == SZ_64K && !(id & ID2_PTFS_64K)) ||
2417                     (PAGE_SIZE != SZ_4K && PAGE_SIZE != SZ_64K)) {
2418                         dev_err(smmu->dev, "CPU page size 0x%lx unsupported\n",
2419                                 PAGE_SIZE);
2420                         return -ENODEV;
2421                 }
2422         }
2423
2424         if (smmu->features & ARM_SMMU_FEAT_TRANS_S1)
2425                 dev_notice(smmu->dev, "\tStage-1: %lu-bit VA -> %lu-bit IPA\n",
2426                            smmu->s1_input_size, smmu->s1_output_size);
2427
2428         if (smmu->features & ARM_SMMU_FEAT_TRANS_S2)
2429                 dev_notice(smmu->dev, "\tStage-2: %lu-bit IPA -> %lu-bit PA\n",
2430                            smmu->s2_input_size, smmu->s2_output_size);
2431
2432         return 0;
2433 }
2434
2435 #define defreg(_name)                           \
2436         {                                       \
2437                 .name = __stringify(_name),     \
2438                 .offset = ARM_SMMU_ ## _name,   \
2439         }
2440 #define defreg_gr0(_name) defreg(GR0_ ## _name)
2441
2442 static const struct debugfs_reg32 arm_smmu_gr0_regs[] = {
2443         defreg_gr0(sCR0),
2444         defreg_gr0(ID0),
2445         defreg_gr0(ID1),
2446         defreg_gr0(ID2),
2447         defreg_gr0(sGFSR),
2448         defreg_gr0(sGFSYNR0),
2449         defreg_gr0(sGFSYNR1),
2450         defreg_gr0(sTLBGSTATUS),
2451         defreg_gr0(PIDR2),
2452 };
2453
2454 static ssize_t smmu_context_filter_write(struct file *file,
2455                                          const char __user *user_buf,
2456                                          size_t count, loff_t *ppos)
2457 {
2458         u8 cbndx;
2459         char buf[] = __stringify(ARM_SMMU_MAX_CBS);
2460         size_t bytes = min_t(size_t, sizeof(buf), count);
2461         struct seq_file *seqf = file->private_data;
2462         struct arm_smmu_device *smmu = seqf->private;
2463         unsigned long *bitmap = smmu->context_filter;
2464
2465         if (kstrtou8_from_user(user_buf, bytes, 10, &cbndx)) {
2466                 size_t bytes;
2467
2468                 bytes = BITS_TO_LONGS(ARM_SMMU_MAX_CBS) * sizeof(long);
2469                 memset(bitmap, 0, bytes);
2470                 dev_info(smmu->dev, "resetting context_filter\n");
2471                 return count;
2472         }
2473
2474         if (cbndx > smmu->num_context_banks)
2475                 return -EINVAL;
2476
2477         set_bit(cbndx, bitmap);
2478         return count;
2479 }
2480
2481 static int smmu_context_filter_show(struct seq_file *s, void *unused)
2482 {
2483         struct arm_smmu_device *smmu = s->private;
2484         unsigned long *bitmap = smmu->context_filter;
2485         int idx = 0;
2486
2487         while (1) {
2488                 idx = find_next_bit(bitmap, ARM_SMMU_MAX_CBS, idx);
2489                 if (idx >= ARM_SMMU_MAX_CBS)
2490                         break;
2491                 seq_printf(s, "%d ", idx);
2492                 idx++;
2493         }
2494         seq_putc(s, '\n');
2495         return 0;
2496 }
2497
2498 static int smmu_context_filter_open(struct inode *inode, struct file *file)
2499 {
2500         return single_open(file, smmu_context_filter_show, inode->i_private);
2501 }
2502
2503 static const struct file_operations smmu_context_filter_fops = {
2504         .open           = smmu_context_filter_open,
2505         .read           = seq_read,
2506         .write          = smmu_context_filter_write,
2507         .llseek         = seq_lseek,
2508         .release        = single_release,
2509 };
2510
2511 static void arm_smmu_debugfs_delete(struct arm_smmu_device *smmu)
2512 {
2513         int i;
2514         const struct debugfs_reg32 *regs = smmu->regset->regs;
2515
2516         regs += ARRAY_SIZE(arm_smmu_gr0_regs);
2517         for (i = 0; i < 4 * smmu->num_context_banks; i++)
2518                 kfree(regs[i].name);
2519
2520         kfree(smmu->regset);
2521         debugfs_remove_recursive(smmu->debugfs_root);
2522 }
2523
2524 static void arm_smmu_debugfs_create(struct arm_smmu_device *smmu)
2525 {
2526         int i;
2527         struct debugfs_reg32 *regs;
2528         size_t bytes;
2529
2530         smmu->debugfs_root = debugfs_create_dir(dev_name(smmu->dev), NULL);
2531         if (!smmu->debugfs_root)
2532                 return;
2533
2534         smmu->masters_root = debugfs_create_dir("masters", smmu->debugfs_root);
2535         if (!smmu->masters_root)
2536                 goto err_out;
2537
2538         bytes = (smmu->num_context_banks + 1) * sizeof(*smmu->regset);
2539         bytes += ARRAY_SIZE(arm_smmu_gr0_regs) * sizeof(*regs);
2540         bytes += 4 * smmu->num_context_banks * sizeof(*regs);
2541         smmu->regset = kzalloc(bytes, GFP_KERNEL);
2542         if (!smmu->regset)
2543                 goto err_out;
2544
2545         smmu->regset->base = smmu->base;
2546         smmu->regset->nregs = ARRAY_SIZE(arm_smmu_gr0_regs) +
2547                 4 * smmu->num_context_banks;
2548         smmu->regset->regs = (struct debugfs_reg32 *)(smmu->regset +
2549                                                 smmu->num_context_banks + 1);
2550         regs = (struct debugfs_reg32 *)smmu->regset->regs;
2551         for (i = 0; i < ARRAY_SIZE(arm_smmu_gr0_regs); i++) {
2552                 regs->name = arm_smmu_gr0_regs[i].name;
2553                 regs->offset = arm_smmu_gr0_regs[i].offset;
2554                 regs++;
2555         }
2556
2557         for (i = 0; i < smmu->num_context_banks; i++) {
2558                 regs->name = kasprintf(GFP_KERNEL, "GR0_SMR%03d", i);
2559                 regs->offset = ARM_SMMU_GR0_SMR(i);
2560                 regs++;
2561
2562                 regs->name = kasprintf(GFP_KERNEL, "GR0_S2CR%03d", i);
2563                 regs->offset = ARM_SMMU_GR0_S2CR(i);
2564                 regs++;
2565
2566                 regs->name = kasprintf(GFP_KERNEL, "GR1_CBAR%03d", i);
2567                 regs->offset = (1 << smmu->pgshift) + ARM_SMMU_GR1_CBAR(i);
2568                 regs++;
2569
2570                 regs->name = kasprintf(GFP_KERNEL, "GR1_CBA2R%03d", i);
2571                 regs->offset = (1 << smmu->pgshift) + ARM_SMMU_GR1_CBA2R(i);
2572                 regs++;
2573         }
2574
2575         debugfs_create_regset32("regdump", S_IRUGO, smmu->debugfs_root,
2576                                 smmu->regset);
2577         debugfs_create_file("context_filter", S_IRUGO | S_IWUSR,
2578                             smmu->debugfs_root, smmu,
2579                             &smmu_context_filter_fops);
2580         debugfs_create_bool("skip_mapping",  S_IRUGO | S_IWUSR,
2581                             smmu->debugfs_root, &arm_smmu_skip_mapping);
2582         debugfs_create_bool("gr0_tlbiallnsnh",  S_IRUGO | S_IWUSR,
2583                         smmu->debugfs_root, &arm_smmu_gr0_tlbiallnsnh);
2584         return;
2585
2586 err_out:
2587         arm_smmu_debugfs_delete(smmu);
2588 }
2589
2590 static struct of_device_id arm_smmu_of_match[] = {
2591         { .compatible = "arm,smmu-v1", .data = (void *)ARM_SMMU_V1 },
2592         { .compatible = "arm,smmu-v2", .data = (void *)ARM_SMMU_V2 },
2593         { .compatible = "arm,mmu-400", .data = (void *)ARM_SMMU_V1 },
2594         { .compatible = "arm,mmu-401", .data = (void *)ARM_SMMU_V1 },
2595         { .compatible = "arm,mmu-500", .data = (void *)ARM_SMMU_V2 },
2596         { },
2597 };
2598 MODULE_DEVICE_TABLE(of, arm_smmu_of_match);
2599
2600 static int arm_smmu_device_dt_probe(struct platform_device *pdev)
2601 {
2602         const struct of_device_id *of_id;
2603         struct resource *res;
2604         struct arm_smmu_device *smmu;
2605         struct device *dev = &pdev->dev;
2606         struct rb_node *node;
2607         struct of_phandle_args masterspec;
2608         int num_irqs, i, err, count;
2609
2610         if (tegra_platform_is_unit_fpga())
2611                 return -ENODEV;
2612
2613         smmu = devm_kzalloc(dev, sizeof(*smmu), GFP_KERNEL);
2614         if (!smmu) {
2615                 dev_err(dev, "failed to allocate arm_smmu_device\n");
2616                 return -ENOMEM;
2617         }
2618         smmu_handle = smmu;
2619         smmu->dev = dev;
2620
2621         INIT_LIST_HEAD(&smmu->asprops);
2622         count = tegra_smmu_of_register_asprops(smmu->dev, &smmu->asprops);
2623         if (!count) {
2624                 dev_err(dev, "invalid domains property\n");
2625                 return -EINVAL;
2626         }
2627
2628         of_id = of_match_node(arm_smmu_of_match, dev->of_node);
2629         smmu->version = (enum arm_smmu_arch_version)of_id->data;
2630
2631         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
2632         smmu->base = devm_ioremap_resource(dev, res);
2633         if (IS_ERR(smmu->base))
2634                 return PTR_ERR(smmu->base);
2635         smmu->size = resource_size(res);
2636
2637         if (of_property_read_u32(dev->of_node, "#global-interrupts",
2638                                  &smmu->num_global_irqs)) {
2639                 dev_err(dev, "missing #global-interrupts property\n");
2640                 return -ENODEV;
2641         }
2642
2643         num_irqs = 0;
2644         while ((res = platform_get_resource(pdev, IORESOURCE_IRQ, num_irqs))) {
2645                 num_irqs++;
2646                 if (num_irqs > smmu->num_global_irqs)
2647                         smmu->num_context_irqs++;
2648         }
2649
2650         if (!smmu->num_context_irqs) {
2651                 dev_err(dev, "found %d interrupts but expected at least %d\n",
2652                         num_irqs, smmu->num_global_irqs + 1);
2653         }
2654
2655         smmu->irqs = devm_kzalloc(dev, sizeof(*smmu->irqs) * num_irqs,
2656                                   GFP_KERNEL);
2657         if (!smmu->irqs) {
2658                 dev_err(dev, "failed to allocate %d irqs\n", num_irqs);
2659                 return -ENOMEM;
2660         }
2661
2662         for (i = 0; i < num_irqs; ++i) {
2663                 int irq = platform_get_irq(pdev, i);
2664
2665                 if (irq < 0) {
2666                         dev_err(dev, "failed to get irq index %d\n", i);
2667                         return -ENODEV;
2668                 }
2669                 smmu->irqs[i] = irq;
2670         }
2671
2672         err = arm_smmu_device_cfg_probe(smmu);
2673         if (err)
2674                 return err;
2675
2676         i = 0;
2677         smmu->masters = RB_ROOT;
2678         while (!of_parse_phandle_with_args(dev->of_node, "mmu-masters",
2679                                            "#stream-id-cells", i,
2680                                            &masterspec)) {
2681
2682                 dev_dbg(dev, "%s() masterspec.np->name=%s\n",
2683                         __func__, masterspec.np->name);
2684
2685                 err = register_smmu_master(smmu, dev, &masterspec);
2686                 if (err) {
2687                         dev_err(dev, "failed to add master %s\n",
2688                                 masterspec.np->name);
2689                         goto out_put_masters;
2690                 }
2691
2692                 i++;
2693         }
2694         dev_notice(dev, "registered %d master devices\n", i);
2695
2696         parse_driver_options(smmu);
2697
2698         if (smmu->version > ARM_SMMU_V1 &&
2699             smmu->num_context_banks != smmu->num_context_irqs) {
2700                 dev_info(dev,
2701                         "found only %d context interrupt(s) but %d required\n",
2702                         smmu->num_context_irqs, smmu->num_context_banks);
2703         }
2704
2705         for (i = 0; i < smmu->num_global_irqs; ++i) {
2706                 err = request_irq(smmu->irqs[i],
2707                                   arm_smmu_global_fault,
2708                                   IRQF_SHARED,
2709                                   "arm-smmu global fault",
2710                                   smmu);
2711                 if (err) {
2712                         dev_err(dev, "failed to request global IRQ %d (%u)\n",
2713                                 i, smmu->irqs[i]);
2714                         goto out_free_irqs;
2715                 }
2716         }
2717
2718         INIT_LIST_HEAD(&smmu->list);
2719         spin_lock(&arm_smmu_devices_lock);
2720         list_add(&smmu->list, &arm_smmu_devices);
2721         spin_unlock(&arm_smmu_devices_lock);
2722
2723         arm_smmu_device_reset(smmu);
2724         arm_smmu_debugfs_create(smmu);
2725         return 0;
2726
2727 out_free_irqs:
2728         while (i--)
2729                 free_irq(smmu->irqs[i], smmu);
2730
2731 out_put_masters:
2732         for (node = rb_first(&smmu->masters); node; node = rb_next(node)) {
2733                 struct arm_smmu_master *master
2734                         = container_of(node, struct arm_smmu_master, node);
2735                 of_node_put(master->of_node);
2736         }
2737
2738         return err;
2739 }
2740
2741 static int arm_smmu_device_remove(struct platform_device *pdev)
2742 {
2743         int i;
2744         struct device *dev = &pdev->dev;
2745         struct arm_smmu_device *curr, *smmu = NULL;
2746         struct rb_node *node;
2747
2748         arm_smmu_debugfs_delete(smmu);
2749         spin_lock(&arm_smmu_devices_lock);
2750         list_for_each_entry(curr, &arm_smmu_devices, list) {
2751                 if (curr->dev == dev) {
2752                         smmu = curr;
2753                         list_del(&smmu->list);
2754                         break;
2755                 }
2756         }
2757         spin_unlock(&arm_smmu_devices_lock);
2758
2759         if (!smmu)
2760                 return -ENODEV;
2761
2762         for (node = rb_first(&smmu->masters); node; node = rb_next(node)) {
2763                 struct arm_smmu_master *master
2764                         = container_of(node, struct arm_smmu_master, node);
2765                 of_node_put(master->of_node);
2766         }
2767
2768         if (!bitmap_empty(smmu->context_map, ARM_SMMU_MAX_CBS))
2769                 dev_err(dev, "removing device with active domains!\n");
2770
2771         for (i = 0; i < smmu->num_global_irqs; ++i)
2772                 free_irq(smmu->irqs[i], smmu);
2773
2774         /* Turn the thing off */
2775         writel(sCR0_CLIENTPD, ARM_SMMU_GR0_NS(smmu) + ARM_SMMU_GR0_sCR0);
2776         return 0;
2777 }
2778
2779 static struct platform_driver arm_smmu_driver = {
2780         .driver = {
2781                 .owner          = THIS_MODULE,
2782                 .name           = "arm-smmu",
2783                 .of_match_table = of_match_ptr(arm_smmu_of_match),
2784         },
2785         .probe  = arm_smmu_device_dt_probe,
2786         .remove = arm_smmu_device_remove,
2787 };
2788
2789 static int __init arm_smmu_init(void)
2790 {
2791         int ret;
2792
2793 #ifdef CONFIG_ARM_SMMU_WAR
2794         if (tegra_platform_is_linsim()) {
2795                 mc_base = ioremap_nocache(MC_BASE, MC_SIZE);
2796                 if (!mc_base)
2797                         return -EINVAL;
2798
2799                 pr_info("%s(): 0x%08x is mapped to %p\n",
2800                         __func__, MC_BASE, mc_base);
2801                 __writel(SMMU_CONFIG_ENABLE, mc_base + SMMU_CONFIG);
2802         }
2803 #endif
2804         ret = platform_driver_register(&arm_smmu_driver);
2805         if (ret)
2806                 return ret;
2807
2808         /* Oh, for a proper bus abstraction */
2809         if (!iommu_present(&platform_bus_type))
2810                 bus_set_iommu(&platform_bus_type, &arm_smmu_ops);
2811
2812 #ifdef CONFIG_ARM_AMBA
2813         if (!iommu_present(&amba_bustype))
2814                 bus_set_iommu(&amba_bustype, &arm_smmu_ops);
2815 #endif
2816
2817 #ifdef CONFIG_PCI
2818         if (!iommu_present(&pci_bus_type))
2819                 bus_set_iommu(&pci_bus_type, &arm_smmu_ops);
2820 #endif
2821
2822         return 0;
2823 }
2824
2825 static void __exit arm_smmu_exit(void)
2826 {
2827         return platform_driver_unregister(&arm_smmu_driver);
2828 }
2829
2830 subsys_initcall(arm_smmu_init);
2831 module_exit(arm_smmu_exit);
2832
2833 MODULE_DESCRIPTION("IOMMU API for ARM architected SMMU implementations");
2834 MODULE_AUTHOR("Will Deacon <will.deacon@arm.com>");
2835 MODULE_LICENSE("GPL v2");